在 Laravel 中为 private/public 所有权创建一个简单的后端设计
creating a simple back end design in Laravel for private/public ownership
我将 Laravel 用于一个站点,其中大多数数据库对象可以是私有的(即,只能由其所有者查看)或 public(每个人都可以查看,包括来宾)。其中每个都有一个 user_id
,当对象为 public.
时,我将其设置为 NULL
在这种情况下验证路由的最简单方法是什么?例如,在 /routes/web.php
我有:
Route::get('/{tournament}/players', [TournamentController::class, 'indexPlayers']);
我想确保 tournament->user_id
是 NULL
或对应于用户的 ID。我能够通过在 /app/Providers/RouteServiceProvider.php
:
中显式绑定 tournament
来做到这一点
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
中执行此操作吗?
首先,现在有语法 Auth::id()
可以用作 Auth::user()->id ?? NULL
的 shorthand,这样可以省去一些麻烦。
接下来,我最终将逻辑移出 RouteServiceProvider.php
并移入控制器,这样我就可以明确控制 public 与私有对象发生的情况:
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
}
}
...
}
我将 Laravel 用于一个站点,其中大多数数据库对象可以是私有的(即,只能由其所有者查看)或 public(每个人都可以查看,包括来宾)。其中每个都有一个 user_id
,当对象为 public.
NULL
在这种情况下验证路由的最简单方法是什么?例如,在 /routes/web.php
我有:
Route::get('/{tournament}/players', [TournamentController::class, 'indexPlayers']);
我想确保 tournament->user_id
是 NULL
或对应于用户的 ID。我能够通过在 /app/Providers/RouteServiceProvider.php
:
tournament
来做到这一点
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
中执行此操作吗?
首先,现在有语法 Auth::id()
可以用作 Auth::user()->id ?? NULL
的 shorthand,这样可以省去一些麻烦。
接下来,我最终将逻辑移出 RouteServiceProvider.php
并移入控制器,这样我就可以明确控制 public 与私有对象发生的情况:
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
}
}
...
}