Skip to content

How to Set Variables in Blade Templates

set variable blade laravel

Let’s quickly look at how we can set variables in Blade templates.

Here we have some simple HTML where we output the name John Doe.

But we want to store this name inside a variable.

We have a couple of options.

 

We can declare the variable in line like this:

Or if we happen to set multiple variables in this file, it’s good to have them visible all in one place.

Usually at the top of the file.

Here we can use the @php Blade directive.


⚠️ Just a quick mention, while we can use the vanilla PHP syntax instead of the Blade directive, it is not recommended.

Don’t use this syntax in modern Blade templates. It’s bad JuJu.

 

Happy coding 😊

 


Let me know what you think about this article in the comments section below.

If you find this article helpful, please share it with others and subscribe to the blog to support me, and receive a bi-monthly-ish e-mail notification on my latest articles.   
  

Comments

Tags: