Blade::if() Directives

Tutorials

July 12th, 2017

blade-if.png

A new Blade addition in Laravel 5.5 will add support for simplifying custom if statements in your views.

The syntax might something like this in your AppServiceProvider::boot() method:

1use Illuminate\Support\Facades\Blade;
2
3Blade::if('admin', function () {
4 return auth()->check() && auth()->user()->isAdmin();
5});

The new Blade::if() makes it convenient to abstract repetitive checks out of templates, making them more readable:

1@admin
2 <a href="{{ route('super.secret') }}">Secret Page</a>
3@else
4 Welcome Guest. <a href="{{ route('login') }}">Login</a>
5@endadmin

In previous versions of Laravel, you would have to write a bit more code. For example, David Hemphill tweeted some really cool directives using this technique in Laravel 5.4:

???? Go crazy with Blade directives. The simplest things can abstract away tons of visual noise from your templates. pic.twitter.com/p5udGWJkhd

— David Hemphill (@davidhemphill) June 22, 2017

Which is now simplified even more in Laravel 5.5:

1Blade::if('prod', function () {
2 return app()->environment('production');
3});

You can also pass arguments to make the checks more dynamic:

1Blade::if('env', function ($env) {
2 return app()->environment($env);
3});

Which would then look like this in your templates:

1@env('production')
2 <script src="some-prod.js"></script>
3@endenv

If you want to learn more about Blade::if(), Laracasts has a video tutorial on it, and we look forward to seeing what you’ll come up with!

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.