A
A
Anton2019-05-30 18:18:49
Laravel
Anton, 2019-05-30 18:18:49

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');

I'm trying to restrict access in the controller, but I'm doing something wrong
if (auth()->id() != $user->id || !auth()->user()->isAdmin) {
    abort(403);
}

If you leave only the first part of the comparison, then it works as expected, but only for a normal user who cannot see other people's orders
if (auth()->id() != $user->id) {
    abort(403);
}

I would be very grateful for a hint on how to do it right - so that all orders are open for the admin, and only his own for a regular user.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vasyl Fomin, 2019-05-30
@tohin15

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

Now, with each call to orders, the condition will be checked whether the user is an admin, if not, the condition $builder->where('user_id', $user->id) will be added to the request.
It’s not very good to use such logic in models, but it was convenient for me, and the problem was solved, + it works when updating, deleting, viewing one, viewing a list and there is nothing to write additionally.

J
jazzus, 2019-05-30
@jazzus

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...
}

In the route, you
probably need user_id instead of user
And that means looking for a user, how
Orders are tied to a user through a hasMany relation and are requested
$orders = $user->orders;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question