Assigning a Variable in a Blade Template


You want to assign a variable in a Blade template.


Blade does not provide a command to do this.

The idea is to cleanly separate logic from presentation. But in the case where it’s more expedient to assign a variable in a template, here’s a couple tricks.

You can always use the PHP tags.

<?php $var = 'test'; ?>
{{ $var }}

Or, you can use a Blade comment with a special syntax.

{{--*/ $var = 'test' /*--}}
{{ $var }}

This second method works because Blade comments get translated in the format below.

<?php /*COMMENT*/ ?>

Thus, the above variable assignment gets translated to the following PHP code.

<?php /**/ $var = 'test' /**/ ?>

See Using Comments in Blade Templates.


You also extend Blade adding a new command, such as @setvar.

See the Extending Blade Templates recipe.

About the author