belong to the user's role
That's where the authorized users ID comes in.
public function getPets($petsearch = '')
{
$petsearch = $petsearch . "%";
$query = Pet::where('petname', 'like', $petsearch);
if (Auth::user()->role !== 'admin') {
$userid = Auth::user()->id;
$query->where('ownerid', '=', $userid);
}
$results = $query->orderBy('petname', 'asc')->paginate(5);
return $results;
}
So if admin show all otherwise show only the currently logged in users data.
Multiple roles:
Can write whatever method you see fit to see if a logged in user is also an admin.
I am in no way suggesting to use any of this code.
I wrote one, but do your own the way you want:
public static function userRole($role = null)
{
$userrole = Auth::user()->role;
$checkrole = explode(',', $userrole);
if (in_array($role, $checkrole)) {
return $role;
}
return false;
}
Then to use:
public function getPets($petsearch = '')
{
$petsearch = $petsearch . "%";
$query = Pet::where('petname', 'like', $petsearch);
if (ChkAuth::userRole('admin') === false) {
$userid = Auth::user()->id;
$query->where('ownerid', '=', $userid);
}
$results = $query->orderBy('petname', 'asc')->paginate(5);
return $results;
}
If user is admin this part
if (ChkAuth::userRole('admin') === false) {
$userid = Auth::user()->id;
$query->where('ownerid', '=', $userid);
}
Is not used, since admin will see all.
Again just example of what I did, I am not saying use anything here, write your own logic.
But the key to a user seeing their own data only is:
$query->where('ownerid', '=', $userid);
// or
$query->where('user_id', '=', $userid);
Something like that.
In RBAC there are hundreds of ways to setup, I try to stay simple.
There's nothing in the docs that prevents you from writing some custom methods to check a role.
Also here's an S.O. article: https://stackoverflow.com/questions/44226475/check-if-auth-user-role-id-matches-array-in-laravel