Pooriya Mostaan
Pooriya Mostaan

Reputation: 405

How to check user role and show select option in laravel

I have users with different roles, like Admin,Employee,Secretary,etc.

And i have a page for send letter, in this page i have a select option to show indicators.

I want when user with Secretary role open this page, see all of the indicators but other users with other roles just see one indicator like internal letters, how can i do this ?

I have a relation between role and user :

User Model

public function roles()
{
    return $this->belongsToMany(Role::class);
}

Role Model

public function users()
{
    return $this->belongsToMany(User::class);
}

This is select option in send letter page :

<select class="col-12 border mt-2 pt-2" name="indicator_id">
        @foreach($indicators as $indicator)
                <option value="{{ $indicator->id }}">{{ $indicator->name }}</option>
        @endforeach
</select>

As you can see, indicators comes from somewhere else.

This is Letter Controller to show send letter page :

$indicators = Indicator::all();
return view('Letter.add', compact('indicators'));

Upvotes: 0

Views: 2838

Answers (1)

Makdous
Makdous

Reputation: 1433

Add this function to your User Model which checks for the user role:

   /**
 * Check if this user belongs to a role
 *
 * @return bool
 */
 public function hasRole($role_name)
 {
     foreach ($this->roles as $role){

         //I assumed the column which holds the role name is called role_name
         if ($role->role_name == $role_name)
             return true;
      }
     return false;
 }

Now in your view you call it like so:

<select class="col-12 border mt-2 pt-2" name="indicator_id">
    @foreach($indicators as $indicator)    
          @if (Auth::user()->hasRole('Secretary'))
                <option value="{{ $indicator->id }}">{{ $indicator->name }}</option>
          @elseif (!Auth::user()->hasRole('Secretary') && {{ $indicator->name }} == 'internalLetter')
               <option value="{{ $indicator->id }}">Internal Letter</option>
          @endif
    @endforeach   

</select>

Upvotes: 2

Related Questions