Posts Learn Snippets Categories Tags About
/

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

7 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>

Created 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.