Posts Learn Components new Snippets new Categories Tags About Device Beast sponsor

How to Write Raw PHP Code in Laravel Blade Template

Sometimes it's necessary to write Raw PHP code in your Laravel Blade, so here's how you can define it.

Created on Jul 03, 2021


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

    $navLinks = [
        'Home' => route('home.index'),
        'Contact' => route('contact.index'),
        'About' => route('about.index'),

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

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>

Snippets by

PostSrc poster


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.


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

Other Code Snippets