Home / Snippets / How to Set Variables in a Laravel Blade Template
How to Set Variables in a Laravel Blade Template cover

How to Set Variables in a Laravel Blade Template

4.3K

3 years ago

0 comments

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" }}
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