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

200

2 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

Ahmad Aziz

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

Post Tutorials

Learn trending tutorials for ReactJs, React Native, VueJS, NextJs, Laravel, Tailwind CSS, and Flutter development.
View Tutorials

Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that's right for your web projects
View Components

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this