V4n1ll4
V4n1ll4

Reputation: 6099

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.

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();
}

Upvotes: 0

Views: 160

Answers (1)

cbcaio
cbcaio

Reputation: 464

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.

Upvotes: 0

Related Questions