Home / Snippets / How to Write Raw PHP Code in Laravel Blade Template
How to Write Raw PHP Code in Laravel Blade Template cover

How to Write Raw PHP Code in Laravel Blade Template

2.8K

3 years ago

0 comments

To run raw PHP code in Laravel blade you can make use of the "php" directive. Although complex logic should be performed inside the controller, any logic that's necessary to bee defined on the blade can be defined using this method.
# views/partials/menus.blade.php

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

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

Another approach is to define it using a normal "php" opening and closing tag.
<?php $name = "PostSrc"; ?>

And with that, you can call the variable name inside the blade itself after the location of the code definition.
<h1>{{ $name }}</h2>
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