Support the ongoing development of Laravel.io →
Blade Architecture Authorization

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 class="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?

Last updated by @ajax30 3 years ago.
0

You can have a look at https://spatie.be/docs/laravel-permission/v5/introduction and see how they did it. It's basically the same thing you are trying to do and I don't know why you try to reinvent the wheel.

Last updated by @geowrgetudor 3 years ago.
0
Blade::if('hasPermissionTo', function ($permission) {
    return in_array($permission, $this->user_permissions);
});
0
Solution selected by @ajax30

Sign in to participate in this thread!

PHPverse

Your banner here too?

Razvan ajax30 Joined 2 Oct 2021

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.