How to Set Variables in Blade Templates

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 through comments below, or on Twitter at @pelu_carol.

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.

 

You may also like...