What is the correct way to authenticate all routes except login and register when I apply auth middleware in all controllers? Is there a way to apply auth middleware in one place and exclude login, register routes?
You can group all your authenticated routes like following, laravel provides a default middleware for auth and guest users
Route::group(['middleware' => ['auth']], function () {
Route::get('home', 'HomeController@index');
Route::post('save-user', 'UserController@saveUser');
Route::put('edit-user', 'UserController@editUser');
});
The above route names are just made up, please follow a proper naming convention for your routes and controllers. Also read about middlewares over here and about routing over here
You can add middleware to your whole web.php
route file by adding the middleware to your routes mapping in RouteServiceProvider
.
Go to app/Providers/RouteServiceProvider.php
and in mapWebRoutes()
, change middleware('web')
to middleware(['web', 'auth'])
:
protected function mapWebRoutes()
{
Route::middleware(['web', 'auth'])
->namespace($this->namespace)
->group(base_path('routes/web.php'));
}
web.php
file:Create a new method mapAdminRoutes()
:
protected function mapAdminRoutes()
{
Route::middleware(['web', 'auth:admin'])
->namespace('App\Http\Controllers\Admin')
->name('admin.')
->group(base_path('routes/admin.php'));
}
Map it:
public function map()
{
$this->mapWebRoutes();
$this->mapAdminRoutes(); // <-- add this
...
}
Create an admin.php
file in your routes
folder, then create your routes for Admin:
<?php
use Illuminate\Support\Facades\Route;
// This route's name will be 'admin.dashboard'
Route::get('dashboard', 'DashboardController@dashboard')->name('dashboard');
// This route's name will be 'admin.example'
Route::get('example', 'ExampleController@example')->name('example');
...
Now you can configure everything in 1 place, like prefix
, name
, middleware
and namespace
.
Check php artisan route:list
to see the results :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With