Posts Learn Components new Snippets new Categories Tags About Device Beast sponsor
/

How to Write PHP Code inside of Laravel Blade Template

Learn how to write PHP code in Laravel blade to compute your logic

Created on Jun 29, 2021

22 views

Sometimes you might want to write PHP code inside the blade template itself to process some logic or just parse some data in general. To do that there are 2 ways.

Using Regular PHP Tags
The first way is to use regular starting and closing PHP tags like traditionally how it's written.
# views/partials/navbar.blade.php

<?php
    $navLinks = [
        'Home' => route('pages.home'),
        'Contact' => route('pages.contact'),
        'About' => route('pages.about'),
    ];
?>

<div>
    @foreach($navLinks as $name => $link)
        <a href="{{ $link }}">{{ $name }}</a>
    @endforeach
</div>

Using Blade Directive
The second way is to use PHP directive and it starts with @php and ends with @endphp
# views/partials/navbar.blade.php

@php
    $navLinks = [
        'Home' => route('pages.home'),
        'Contact' => route('pages.contact'),
        'About' => route('pages.about'),
    ];
@endphp

<div>
    @foreach($navLinks as $name => $link)
        <a href="{{ $link }}">{{ $name }}</a>
    @endforeach
</div>

Snippets by

PostSrc poster

PostSrc

Full stack developer mainly focusing on the front end side of the web. The main author of PostSrc and loves writing tutorial and guides online.

new

PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that are right for your project.

View Components

Other Code Snippets

More