How to Set Variables in a Laravel Blade Template

duality_ picture duality_ · Oct 22, 2012 · Viewed 362k times · Source

I'm reading the Laravel Blade documentation and I can't figure out how to assign variables inside a template for use later. I can't do {{ $old_section = "whatever" }} because that will echo "whatever" and I don't want that.

I understand that I can do <?php $old_section = "whatever"; ?>, but that's not elegant.

Is there a better, elegant way to do that in a Blade template?

Answer

Pim picture Pim · Sep 2, 2014

LARAVEL 5.5 AND UP

The @php blade directive no longer accepts inline tags. Instead, use the full form of the directive:

@php
$i = 1
@endphp

LARAVEL 5.2 AND UP

You can just use:

@php ($i = 1)

Or you can use it in a block statement:

@php
$i = 1
@endphp

LARAVEL 5

Extend Blade like this:

/*
|--------------------------------------------------------------------------
| Extend blade so we can define a variable
| <code>
| @define $variable = "whatever"
| </code>
|--------------------------------------------------------------------------
*/

\Blade::extend(function($value) {
    return preg_replace('/\@define(.+)/', '<?php ${1}; ?>', $value);
});

Then do one of the following:

Quick solution: If you are lazy, just put the code in the boot() function of the AppServiceProvider.php.

Nicer solution: Create an own service provider. See https://stackoverflow.com/a/28641054/2169147 on how to extend blade in Laravel 5. It's a bit more work this way, but a good exercise on how to use Providers :)

LARAVEL 4

You can just put the above code on the bottom of app/start/global.php (or any other place if you feel that is better).


After the above changes, you can use:

@define $i = 1

to define a variable.