Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

romido's avatar

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();
});
0 likes
5 replies
rodrigo.pedra's avatar
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
romido's avatar

This is exactly what i was looking for, thank you!

2 likes
Sinnbeck's avatar

That is totally fair. If there is only an admin role, you can also do it using a simple helper method on the User model

public function isAdmin()
{
   return $this->role == 'admin';
}

And

@if(Auth::user()->isAdmin())
 <a  class="nav-a m-3" href="{{route('books.create')}}">Add a book</a>
@endif
3 likes

Please or to participate in this conversation.