Laravel blade is a powerful templating engine that gives you a lot of control over your HTML. One thing you can do with blade is declare variables. 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 . For example, to declare a variable called “name”, you would use the following code:
@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.
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. Variables can be declared in a number of ways:
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"
?>