Does the user already have a role? If not you could consider installing spaties permissions package.
Oct 29, 2020
5
Level 2
How to hide parts of your view for users with different roles?
I have a navigation with links and ik want to only show the 'add a book' link to users with the role of admin.
How can i do this in my view using something like this?
view:
@if(Auth::user()->role == "admin")
<a class="nav-a m-3" href="{{route('books.create')}}">Add a book</a>
@endif
user migration:
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->string('role');
$table->rememberToken();
$table->timestamps();
});
Level 56
You could define gates for each role in your app's AuthServiceProvider's boot method:
public function boot()
{
$this->registerPolicies();
Gate::define('admin', function ($user) {
return $user->role == 'admin';
});
Gate::define('user', function ($user) {
return $user->role == 'user';
});
}
Reference: https://laravel.com/docs/8.x/authorization#writing-gates
And then use blade's @\can directive:
@can('admin')
<a class="nav-a m-3" href="{{route('books.create')}}">Add a book</a>
@endcan
Reference: https://laravel.com/docs/8.x/authorization#via-blade-templates
EDIT added a backslash to the @\can directive so I don't tag a Laracast's user account
1 like
Please or to participate in this conversation.