avinash11 liked a comment+100 XP
3mos ago
avinash11 wrote a reply+100 XP
4mos ago
If I understood correctly, when a successful payment goes through for the product (whether it’s a one-time payment or monthly), you set the paid field on the users table to true.
Once this happens, the user should be able to:
- View posts
- Create new forum posts
If this is the case, you can leverage Laravel’s Gate system to control access across your application.
You could use policies as well but here’s the Gate approach through the register() in the AppServiceProvider
use Illuminate\Support\Facades\Gate;
Gate::define('view-post', function ($user) {
return $user->paid;
});
Gate::define('create-post', function ($user) {
return $user->paid;
});
If you later decide to introduce different rules for viewing vs creating posts, you can easily modify these independently. Otherwise, a single rule works perfectly fine.
For the routes, you can use the can middleware:
Route::get('/posts/{post}', [PostController::class, 'show'])
->middleware(['auth', 'can:view-post']);
Route::post('/forum/posts', [ForumController::class, 'store'])
->middleware(['auth', 'can:create-post']);
Laravel will automatically return a 403 Forbidden response if the user does not pass the gate check.
Laravel also provides Blade directives for authorization checks:
@can('view-post')
{{-- Show paid content --}}
@endcan
@can('create-post')
{{-- Show post creation form --}}
@endcan
This allows you to easily hide UI elements from users who don’t have access.
A great resource for understanding Laravel authorization in depth:
https://laracasts.com/series/mastering-permissions-in-laravel
avinash11 wrote a comment+100 XP
4mos ago
Very interesting and resourceful lesson! Learned a lot from this episode (and series so far). I have a question which might sound silly but I can’t wrap my head around why we are assigning an empty object if we have default values for minRange, maxRange, maxAttempts already? Would that be a safeguard if we called the function createGame (or Game object is instantiated) without an object at all?