Custom blade directive @isAdmin in Laravel 5.3+

  1. Create a is_admin column in your user database, only admin can register a user. Allow admin to register user as admin or not.
  2. Open user.php in the app folder and add use Illuminate\Support\Facades\Auth;
  3. Add the following function to the user class:
public function isAdmin()
{
    if (Auth::user() &&  Auth::user()->is_admin == 1) {
        return true;
    }
}

From there we can already check if user is admin in our view like this:

@if(Auth::user()->isAdmin())
    Something that should only be visible to admin
@endif

4. We would like to keep our code elegant so let’s add a custom directive to blade. Open AppServiceProviders.php and add the following code in the boot function:

namespace App\Providers;
 use Illuminate\Support\ServiceProvider;
 use Illuminate\Support\Facades\Schema;
 use Illuminate\Support\Facades\Blade;
 use Illuminate\Support\Facades\Auth;
 class AppServiceProvider extends ServiceProvider
 {
     /**
      * Register any application services.
      *
      * @return void
      */
     public function register()
     {
         Blade::if('isAdmin', function(){
             if(Auth::check())
                 return Auth::user()->is_admin===1?true:false;
             else return false;
         });
     }
 /**  * Bootstrap any application services.  *  
* @return void  */ 
public function boot() {
     Schema::defaultStringLength(191);
    // Blade custom directives for isAdmin
     Blade::directive('isAdmin', function() {
         return "<?php if(Auth::user()->isAdmin()): ?>";
     });
     Blade::directive('endisAdmin', function() {
             return "<?php endif; ?>";
     }); }
 }

From there you should be all set to use @isAdmin @endisAdmin in your blade view files.

In case it doesn’t work, make sure to test that @if(Auth::user()->isAdmin()) is working properly and revert back to your custom directive.