Posts Learn Components Snippets Categories Tags Tools 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

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

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

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

Sponsors 👑

+ Add Yours
)