How to Set a Variable in Laravel Blade Template?

If you are new to laravel then declaring a variable in the blade template could be confusing. In short, you can declare a variable like this.

@php
    $name = "Jonny";
@endphp

And then use it like this.

<p>Hi there {{ $name }} </p>

Laravel uses the Blade template engine to generate the HTML. It allows us to use HTML and PHP code directly in our template.

In most cases, we pass our variables from your controller to Blade views, but there are some cases we might want to set a variable directly in your Blade view.

Let’s look at, how we pass variables from a controller?

return view('home', ['name' => 'Jonny']);

This function will return the home.blade.php template, where the name variable will be passed and can be directly accessed in HTML.

<p> Welcome {{ $name }}!</p>

We already saw how to set variables directly inside the blade template at the beginning of this tutorial.
Though we could use exact PHP syntax in blade template like below.

<?php 
    $name = "Jonny";
?>

But this is preferable to stick to the Blade PHP block;