Laravel 5.5 New Feature - BladeIf Directive Example

By Hardik Savani November 5, 2023 Category : PHP Laravel

Laravel 5.5 release their official documentation and they added several new features. In this post i will explain one new feature "BladeIf Directive" from the laravel 5.5 list.

BladeIf is a one of the if condition but if you require many time same if condition then you don't need to write same code everywhere. You have to simple put code on one place and use every time name. For example if you have to check user is login or not and is admin then you will always write two condition with code. So we can just define one time and use their name on blade file.

Here, bellow i will give you example of BladeIf Directive from scratch so you can understand how it works and how you can use in your application.

Add Your If Condition:

Laravel 5.5 introduce Blade::if directive and we have to write our command if condition in AppServiceProvider file. So let's open AppServiceProvider.php file and put bellow code.

In this if condition i will check user is login or not and use is admin or not. So you have to add like as bellow example:

app/Providers/AppServiceProvider.php

<?php


namespace App\Providers;


use Illuminate\Support\ServiceProvider;

use Illuminate\Support\Facades\Blade;


class AppServiceProvider extends ServiceProvider

{

/**

* Bootstrap any application services.

*

* @return void

*/

public function boot()

{

Blade::if('is_admin', function () {

return auth()->check() && auth()->user()->isAdmin();

});

}


/**

* Register any application services.

*

* @return void

*/

public function register()

{


}

}

Use in Blade:

Now we have to use "id_admin" blade is Directive in our view file. So it is very simple to use it and you can use again again with just name. So it could be very easy. So let's see how we have to use it.

resources/views/myblade.blade.php

<!DOCTYPE html>

<html>

<head>

<title>Laravel 5.5 Example</title>

<meta charset="utf-8">

<meta http-equiv="X-UA-Compatible" content="IE=edge">

<meta name="viewport" content="width=device-width, initial-scale=1">

</head>

<body>


<h1>Laravel 5.5 New Feature - BladeIf Directive Example</h1>


@is_admin

<p>User is LoggedIn and Admin.</p>

@else

<p>User is not Logged in.</p>

@endis_admin


</body>

</html>

As you see above full example,

i hope it can help you....

Shares