强制 Laravel 模型在获取之前检查所有权
Force Laravel model to check ownership before fetching
我不确定如何实现这一点,但我想要一个中间件、特征或任何可以强制对指定模型进行所有权检查的东西。例如,我想这样做:
Posts::all()
但是我不想获取所有帖子,而是只想获取当前登录用户的帖子。当然,我可以添加 ::where(['user_id' => auth()->user()->id])
,但我想在更低、更安全的级别上进行管理。
基本上,如果可能的话,我想在我的模型中强制使用这个 where 条件。
您可能想为您的模型写一个 scope class。
例如(在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()
您可以更进一步,使用单独的范围使其更加灵活,允许您查询任何用户的帖子:
/**
* 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()
它们很灵活,因为您可以在它们之后添加额外的查询位:
Post::owner(1234)->orderBy('date')->whereModified(null); // etc
发挥你的想象力。 :-)
我不确定如何实现这一点,但我想要一个中间件、特征或任何可以强制对指定模型进行所有权检查的东西。例如,我想这样做:
Posts::all()
但是我不想获取所有帖子,而是只想获取当前登录用户的帖子。当然,我可以添加 ::where(['user_id' => auth()->user()->id])
,但我想在更低、更安全的级别上进行管理。
基本上,如果可能的话,我想在我的模型中强制使用这个 where 条件。
您可能想为您的模型写一个 scope class。
例如(在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()
您可以更进一步,使用单独的范围使其更加灵活,允许您查询任何用户的帖子:
/**
* 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()
它们很灵活,因为您可以在它们之后添加额外的查询位:
Post::owner(1234)->orderBy('date')->whereModified(null); // etc
发挥你的想象力。 :-)