Reputation: 259
I would like to ask you if it is correct way how to use authentication in laravel 8?
I want to make web which will be visible just for logeddin users.
My solution is here. But I want to know if I will have more routes is there some way how to do it with one command and no need to add for each route?
Route::get('/', [PagesController::class,'index'])
->middleware('auth');
Route::get('edit/{id}', [PagesController::class,'editPage'])
->middleware('auth')
->where('id', '[0-9]+');
Route::post('edit/{id}', [PagesController::class,'editItem'])
->middleware('auth')
->where('id', '[0-9]+');
Route::get('delete/{id}', [PagesController::class,'deletePage'])
->middleware('auth')
->where('id', '[0-9]+');
Route::post('delete/{id}', [PagesController::class,'deleteItem'])
->middleware('auth')
->where('id', '[0-9]+');
require __DIR__.'/auth.php';
Thank you
Upvotes: 0
Views: 2123
Reputation: 69
At App\Providers\RouteServiceProvider define
public function boot()
{
Route::pattern('id', '[0-9]+');
}
Once the pattern has been defined, it is automatically applied to all routes using that parameter name:
Route::get('/user/{id}', function ($id) {
// Only executed if {id} is numeric...
});
Than you can create route group with middleware('auth')
Route::middleware(['auth'])->group(function () {
//all of your routes
}
Upvotes: 1
Reputation: 124
You can use route groups, Laravel's documentation is here; https://laravel.com/docs/8.x/routing#route-group-middleware
Your example could be updated to:
Route::middleware(['auth'])->group(function () {
Route::get('/', [PagesController::class,'index']);
Route::get('edit/{id}', [PagesController::class,'editPage'])
->where('id', '[0-9]+');
Route::post('edit/{id}', [PagesController::class,'editItem']);
->where('id', '[0-9]+');
Route::get('delete/{id}', [PagesController::class,'deletePage'])
->where('id', '[0-9]+');
Route::post('delete/{id}', [PagesController::class,'deleteItem'])
->where('id', '[0-9]+');
});
You could go one step further and use Global Constraints to define the id
as [0-9]+
on a global level, instead of each route.
Upvotes: 4