简体   繁体   中英

Laravel 5 scope for selecting rows based on user role

I have a timesheet application which I have written in Laravel 5. I now want to select timesheets based on the user permissions (role). I have 3 levels of user.

  • User
  • Admin
  • Supervisor

A Supervisor supersedes a User . Admin supersedes a Supervisor .

The admin user should be able to see ALL user timesheets. The supervisor should only be able to see timesheets of users associated with them. Users will only be abl to see their own timesheets.

I have the following method setup to select timesheets awaiting approval. This method only works for the User level at the moment as I have added a whereUserId clause.

How can I make the following method work for all roles of user (admin, user, supervisor)?

/**
 * Load timesheets awaiting approval.
 *
 */
public function timesheetsAwaitingApproval() 
{
    return $this->timesheet->whereUserId($this->userid)->whereStatus('Submitted')->get();
}

Try using the hasManyThrough relationship between your models to get the timesheets you need, check the doc . Of course, this will only work if you

Supervisor example

public function timesheets()
{
    return $this->hasManyThrough('Timesheet::class', 'User::class', 'timesheet_id', 'user_id');
}

public function timesheetsAwaitingApproval() 
{
    return $this->timesheets->whereStatus('Submitted')->get();
}

Or something like that, thats just an idea that might work for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM