我使用Laravel作为一个站点,其中大多数数据库对象可以是私有的(即,只能由其所有者查看)或公共的(每个人都可以查看,包括客人)。其中每一个都有一个user_id,当对象是公共的时,我将其设置为NULL。
在这种情况下,验证路由的最简单方法是什么?例如,在/routes/web.php中,我有:
Route::get('/{tournament}/players', [TournamentController::class, 'indexPlayers']);我想确保tournament->user_id要么是NULL,要么对应于用户的id。我能够通过在tournament中显式绑定/app/Providers/RouteServiceProvider.php来做到这一点。
Route::bind('tournament', function ($hash) {
$user_id = Auth::user()->id ?? NULL;
return Tournament::where([['hash', $hash], ['user_id', $user_id]])
->orWhere([['hash', $hash], ['user_id', NULL]])
->firstOrFail();
});但是我有一种强烈的感觉,那就是我把事情弄得太复杂了,或者在错误的地方做事。有更好的办法吗?例如,我应该在TournamentController中这样做吗?
发布于 2021-06-11 21:19:49
首先,现在可以使用语法Auth::id()作为Auth::user()->id ?? NULL的缩写,这样就省去了一些麻烦。
接下来,我将逻辑从RouteServiceProvider.php移到控制器中,这样我就可以显式地控制公共对象和私有对象发生了什么:
class TournamentController extends Controller
{
public function indexPlayers(Tournament $tournament)
{
if ($tournament->user_id === NULL) {
// public
} else if ($tournament->user_id === Auth::id()) {
// private
} else {
// unauthorized
}
}
...
}https://stackoverflow.com/questions/67928540
复制相似问题