Belongs to many get all rows (Laravel)

2019-08-07 06:54发布

问题:

I have a User model and a Property model. The user has 3 roles: admin, manager, and broker. The admins can view all properties, while the managers and brokers can only view the properties that are assigned to them. A manager or broker may have many properties and a property may belong to any number of managers and brokers. Here is the properties relationship in my User model:

/**
 * Get all properties belonging to this user.
 *
 * @return [type]            [description]
 */
public function properties()
{
    if ($this->isAdmin()) {
        return Property::all();

    } elseif ($this->isManager() || $this->isBroker()) {
        return $this->belongsToMany('App\Property');

    }

    return null;
}

This works great for retrieving all properties, but if I have to perform select or where statements, I can only do so if the user is not an admin, since the current code returns the entire Collection if the user is an admin. This makes it impossible to use this method for search functionality and any type of constraint.

Obviously, I do not want to create a record in the property_user table for every single property and admin, as that would take up loads of unnecessary space. However, I do not want to have additional logic in my controllers to only call the properties method if the user is a manager or broker, and perform a custom query if the user is an admin.

Is there any way I can return an Illuminate\Database\Eloquent\Relations\BelongsToMany that has every row in it? Or another Laravel object that I can still chain queries to?

回答1:

You will want to return a query object.

public function properties()
{
    if ($this->isAdmin()) {
        return Property::query();
    } elseif ($this->isManager() || $this->isBroker()) {
        return $this->belongsToMany('App\Property');
    }

    return null;
}