I am unsure how to accomplish this, but I would like to have either a middleware, trait or whatever that would force an ownership check on specified models. For instance, I would like to do this:
Posts::all()
But instead of getting all posts, I would like to get only the posts of the current logged user. Of course I could add a ::where(['user_id' => auth()->user()->id])
but I would like to manage that on a lower, more secure level.
Basically, I would like to force this where condition in my model, if possible.
CodePudding user response:
You probably want to write a scope for your model class.
For instance (in Post.php
):
/**
* Example usage:
* Post::ownedByCurrentUser()->get();
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeOwnedByCurrentUser($query) {
return $query->where([
'user_id' => auth()->user()->id,
]);
} // end scopeOwnedByCurrentUser()
You could go a step further and make this more flexible with a separate scope allowing you to query ANY user's posts:
/**
* Example usage:
* // get all posts belonging to a user
* Post::owner(auth()->user()->id)->get();
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param int $userId User ID of owner
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeOwner($query, int $userId) {
return $query->where([
'user_id' => $userId,
]);
} // end scopeOwner()
They're flexible since you can add extra query bits after them:
Post::owner(1234)->orderBy('date')->whereModified(null); // etc
Use your imagination. :-)