Posts Learn Components new Snippets new Categories Tags About
/

How to Set Variables in a Laravel Blade Template

Learn how to set variables in a Laravel blade template the easy way using the php directive

Created on Oct 06, 2021

49 views

To define a variable in the Laravel Blade template you can make use of the @php directive. This directive can be used to define one to many variables and you can define it like the following.

Variable One-Liner


To define your one-liner variable in the Laravle Blade template, you can write your code like below. Do note that this variable is accessible only within this blade file unless it's imported to other blade files.
@php($firstName = 'John';)

<h2>{{ $firstName }}</h2>

Laravel Multiple Variable


To define multiple variables in the Laravel Blade template, you can write it from within the @php directive body. This definition allows you to define a slightly more readable variable. Using this way you can also perform some minimal code logic to process the data.
@php
    $firstName = 'John';
    $lastName = 'Doe';
    $gender = 'Female';

    $fullName = $firstName . ' ' . $lastName;
@endphp

Laravel Blade Variable in Version 7


If you are using Laravel 7 then you can define the variable inline like below.
{{ $thisIsVariable = "You can define a variable using this method in Laravel 7" }}
new

If you like our tutorial, do make sure to support us with some coffee. We need the juice to write the content during the night 🤙🏻