DEV Community

Morcos Gad
Morcos Gad

Posted on • Updated on

Make Custom Blade If Directive - Laravel

Let's start quickly if we want to define admin areas via If Directive We start User.php in Models

public function isAdmin(): bool 
{
  return $this->type === 'admin';
}
Enter fullscreen mode Exit fullscreen mode

in blade use isAdmin()

@if(auth()->user()->isAdmin())
  For Admin
@endif
Enter fullscreen mode Exit fullscreen mode

To make the code more interesting in AppServiceProvider.php

public function boot()
{
   Blade::if('admin', function(){
     return auth()->user()->isAdmin();
   });
}
Enter fullscreen mode Exit fullscreen mode

in blade use @admin

@admin
   For Admin
@endadmin
Enter fullscreen mode Exit fullscreen mode

We can check if the user is logged in or not by check()

public function boot()
{
   Blade::if('admin', function(){
     return auth()->check() && auth()->user()->isAdmin();
   });
}
Enter fullscreen mode Exit fullscreen mode

We can also use else

@admin
  For Admin
@else
  Not Admin
@endadmin
Enter fullscreen mode Exit fullscreen mode

I hope you enjoyed the code.

Top comments (0)