creating a simple back end design in Laravel for private/public ownership

  authentication, backend, database, laravel

I’m using Laravel for a site where most database objects can be private (i.e., viewed only by their owner) or public (viewed by everyone, including guests). Each of these has a user_id, which I set to NULL when the object is public.

What’s the simplest way of authenticating routes for this scenario? For example, in /routes/web.php I have:

Route::get('/{tournament}/players', [TournamentController::class, 'indexPlayers']);

and I want to make sure that tournament->user_id is either NULL or corresponds to the user’s id. I was able to do this by explicitly binding tournament in /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]])

but I have the strong feeling that I’m making it too complicated or doing things in the wrong place. Is there a better way? Should I by doing this inside TournamentController, for example?

Source: Laravel

Leave a Reply