Home > OS >  How can I make a Blade directive that takes a parameter, in Laravel 8?
How can I make a Blade directive that takes a parameter, in Laravel 8?

Time:03-03

I am working on a Laravel 8 application.

I need to make a custom directive for checking user's permissions:

So, in app\Providers\AppServiceProvider.php, I did:

public function boot() {
    Schema::defaultStringLength(191);

    Blade::directive('hasPermissionTo', function ($permission) {
        return in_array($permission, $this->user_permissions);
    });
}

The problem with this, is that inside Blade, hasPermissionTo has to be used with a parameter:

@hasPermissionTo('view-users')
   <h2>Users</h2>
    <table >
        <thead>
            <tr>
                <th>Name</th>
                <th>Email</th>
            </tr>
        </thead>
        @if ($users)
        <tbody>
            @foreach ($users as $user)
            <tr>
                <td>{{ $user->first_name }} {{ $user->last_name }}</td>
                <td>{{ $user->email }}</td>
            </tr>
            @endforeach
        </tbody>
        @endif
    </table>
@endhasPermissionTo

How do I fix this problem?

CodePudding user response:

You can use custom blade directives

Blade::if('hasPermissionTo', function ($permissionToBeChecked) {
    return in_array($permissionToBeChecked, $this->user_permissions);
});

And use like you did.

  • Related