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?
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.
Blade::if('hasPermissionTo', function ($permission) {
return in_array($permission, $this->user_permissions);
});
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community