Answer the question
In order to leave comments, you need to log in
How to check user permissions in Laravel?
Hello! There are orders Orders and users Users. A User can only view his own Orders, but if he is an admin (boolean field in the users - isAdmin table), he can also view the Orders of other users
Route::get('/{user}/orders', '[email protected]')->name('orders.index');
if (auth()->id() != $user->id || !auth()->user()->isAdmin) {
abort(403);
}
if (auth()->id() != $user->id) {
abort(403);
}
Answer the question
In order to leave comments, you need to log in
For a similar task, I did the following: I
created a scope (you can even global) that can be connected in the boot method of the model class. For example:
//...
class Order extends Model
{
protected static function boot()
{
parent::boot();
static::addGlobalScope('owner', function (Builder $builder) {
$user = Auth::user();
if (! $user->isAdmin()) {
$builder->where('user_id', $user->id);
}
});
}
}
You need to google the permission-role schema. Admin-not admin can be defined as
$user = Auth::user();
if ($user->isAdmin) {
// code...
}else{
// code...
}
// не админ
if (!$user->isAdmin) {
// code...
}
$orders = $user->orders;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question