fareez.info

Extending Blade for Role Checks in Laravel

Displaying parts of view based on conditions is super easy in Blade using @if ... @endif conditions. Imagine we are storing the role information as a string in the User model under the role field. We would write something as shown below to check the roles in the blade syntax.

@if(Auth::check() && Auth::user()->role === 'admin')
    ...
@else
    ...
@endif

At times, we need to show a particular part of UI to multiple roles and hide from the remaining roles. So for each case, we would start writing @if conditions as we usually do.

@if(Auth::check() &&
   (Auth::user()->role === 'admin' ||
    Auth::user()->role === 'editor'))
    ...
@else
    ...
@endif

This logic is something we will use throughout the application, it would be great if we can make this reusable, so we can avoid the views from cluttered with complex logic and keep the logic in one place handy for any changes.

Thankfully, Laravel makes it super easy to make Blade extensions and even more easier to create Blade extensions that are just if conditions under the hood. Just add the Blade::if with the closure which has the logic for the if condition in the boot method of the AppServiceProvider.

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Blade;
use Auth;

class AppServiceProvider extends ServiceProvider
{

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        // Blade extenstion for Role
        Blade::if('role', function (string $role) {
            return Auth::check() && Auth::user()->role === $role;
        });
    }
}

Now you can check roles in the view with simple @role syntax sugar.

@role('admin')
    //...
@elserole('editor')
    //...
@else
    //...
@endrole

If you want a part of view to be display for multiple roles, just add the following Blade extenstion to the AppServiceProvider as well.

Blade::if('roles', function (array $roles) {
    return Auth::check() && 
        in_array(Auth::user()->role, $roles, true);
});

This takes in an array and checks if the user has a role that is part of the array. You can use this as shown below.

@roles(['admin', 'editor'])
    //...
@elseroles(['user'])
    //...
@else
    //...
@endroles

Converting business logics into Blade extentions like these can help keep the view very much readable and maintainable.

comments powered by Disqus