Home / Snippets / How to Write PHP Code inside of Laravel Blade Template
How to Write PHP Code inside of Laravel Blade Template cover

How to Write PHP Code inside of Laravel Blade Template

235

3 years ago

0 comments

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

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this