Maxcot
Maxcot

Reputation: 1597

show/hide (laravel) menus depending on roles

I want to have certain menu options visible only to certain users.

I've modified my user table in the standard auth framework by adding two roles - boolean columns: isTeacher and isOnCommittee.

I thought I'd try

  1. create a method in my controller to check if the logged in user has the specific role, and then
  2. in the view, call the method, and show the menu option, (or not).

It's all well and fine to put a @if (Auth::iSTeacher()) into my view, but where do I put my function?

I did a search for guest() across all files and found this

...\vendor\laravel\framework\src\Illuminate\Contracts\Auth\Guard.php:
public function guest();

/**
 * Get the currently authenticated user.
 *
 * @return \Illuminate\Contracts\Auth\Authenticatable|null
 */

I understand the purpose of a guard is protect a route, so this is not the place for it.

Where am I supposed to be creating my function?

(if you didn't guess - I'm very new to laravel.

Upvotes: 1

Views: 5451

Answers (2)

Rinon
Rinon

Reputation: 579

My preferred way to do this would be with Authorization via the Gate Facade. You can define so-called "abilities" in AuthServiceProvider like this:

public function boot(GateContract $gate)
{
    $this->registerPolicies($gate);

    $gate->define('update-post', function ($user, $post) {
        return $user->id === $post->user_id;
    });
}

Than inside views you can check:

@can('update-post', $post)
    <a href="/post/{{ $post->id }}/edit">Edit Post</a>
@endcan

Source: https://laravel.com/docs/5.2/authorization#within-blade-templates

Upvotes: 4

Ariful Haque
Ariful Haque

Reputation: 3750

You can use Query Scopes functions in your User model. e.g. write your isTeacher() in User model and in view check

@if(Auth::user()->isTeacher)
   YOUR CODE HERE
@end if

Upvotes: 1

Related Questions