Creating new variables in Laravel’s Blade without resorting to writing PHP code
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!