mercredi 18 juillet 2018

Best way to check if user 'owns' another user

I have implemented a system in Laravel where a user can be a manager of multiple 'stores'. A store can have multiple users belonging to that store. Here's my stripped down table structure -

users

  • id (int)
  • name (string)
  • email (string)

user_stores

  • user_id (int)
  • store_id (int)
  • manager (boolean/tinyint)

stores

  • id (int)
  • name (string)

My issue is checking who a user with a manager pivot flag can manage. I have a solution but I'm not sure it's optimal. I want the query to be as lean as possible. Here is my current solution -

protected $manageable_users;

public function getManageableUserIds () {

    if(!is_array($this->manageable_users)) {

        // get our store id's that we manage
        $manages = DB::table('user_stores')
            ->where('user_id', $this->id)
            ->where('manager', true)
            ->select('store_id');

        // make a join so we can get our data
        $this->manageable_users = DB::table('user_stores AS d2')
            ->joinSub($manages, 'stores', function ($join) {
                $join->on('d2.store_id', '=', 'stores.dealership_id');
            })->distinct()->pluck('d2.user_id')->toArray();
    }

    return $this->manageable_users;
}

So what I'm doing here is grabbing an array of all user ID's that the manager can possibly manage. I then store this as a protected variable so that on the same request I can perform this check multiple times within the same request without making multiple queries.

I then have a separate method called canManage which checks if the current user object can actually manage the passed user -

public function canManage(User $user) {
    // check if our user is manageable
    return in_array($user->id, $this->getManageableUserIds(), true);
}

Now I know Laravel is super smart and for some reason I feel like this isn't the best solution.. plus I don't want it to be too intensive on the database as ultimately there will be a lot of users and stores on this system.

If nothing else, maybe this could be a solution for someone else!

Thanks.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire