Creating new variables in Laravel’s Blade without resorting to writing PHP code

Here’s a quick trick in case like me you occasionally need to declare a new variable in a Blade view.

Blade doesn’t natively support declaring new variables within its own syntax, opting to rely solely on the ones explicitly passed to it, which is a bit safer.

One of Blade’s bonuses is that it doesn’t stop you from writing some PHP code in your templates.

But of course, that’s the lazy programmer’s way out — not to mention a purist’s nightmare.

So here’s my quick trick: move the portion of the view that relies on this as-yet-undeclared variable into some sort of partial and include it. Then you can explicitly declare which variables you want it to use.

The downside of this is that the other declared variables available to the parent template aren’t inherited by the partial. But that’s not impossible to overcome, just explicitly pass the variables it needs.

A benefit of this over simply opening PHP tags and declaring a new variable is tighter scoping of your new variables; the variable declared in the @include statement is only available within the partial and doesn’t pollute the namespace available to your entire view stack.

Artisan mode: On!

Edit: Sérgio Castro has suggested extending Blade specifically to add a @set tag. Nice.

I’ve also since found this blade-extensions package by RobinRadic, which has @set among a bunch of other useful additions to Blade.

I have been given the opportunity to learn Laravel over the past 18 months during my day job at isev. They’ve supported my learning with great tools, an awesome team and wonderful clients. If you’re a Laravel developer interested in joining us, please contact me via Twitter.