Laravel blade is a powerful templating engine that gives you a lot of control over your HTML. One thing you can declare variable in laravel blade template easily by using different methds. This can be useful if you want to reuse a piece of data in your template, or if you want to make your template more dynamic. To declare a variable in a blade template, you use the “@php” and “@endphp” symbol and can define the variable as normal .
Declare variable in laravel blade template using @php syntax
For example, to declare a variable called “name”, you would use the following code to declare variable in laravel html
@php
$name = "John"
@endphp
You can then use this variable anywhere in your template by referencing it. For example, to print the value of the “name” variable, you would use the following code: {{ $name }} You can also use blade variables in place of HTML attributes. Above we easily declared and change variable value in blade template laravel
What is a Variable?
A variable is a value that can be changed. In programming, variables are used to store data values. In the Laravel Blade template system, variables are used to store data that can be displayed in the template.
Also Read : How to get laravel application root path ?
How to Set a Variable in a Laravel Blade Template
When working with Blade templates, it’s often necessary to declare variables to make information available to the template. There is two ways to Declare variable in laravel blade template:
Method 1: Laravel blade template @php syntax
In this method we will use @php
and @endphp
tags to set the variable as follow
@php
$name = "John"
@endphp
Method 2: Php tags to declare the variables
In this method we will use <?php
and ?>
tags to set the variable as follow
<?php
$name = "John"
?>