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

26th Jan '162 of your Earth minutes

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 enjoying working with Laravel every day for the past 4 years. If you’re a Laravel developer interested in working with other pragmatic Laravel developers, feel free to reach out on Twitter, I’d love to hear from you, and who knows maybe we could work together on something beautiful.

#notadesigner • Please don't © me

Want to support my work? Please consider sponsoring me on Spred