Debug School

rakesh kumar
rakesh kumar

Posted on

How to use auth middleware in laravel 9

filtering HTTP requests

protect certain routes

validation

Rate limiting

middleware provide a convenient mechanism for filtering HTTP requests entering your application. Authentication middleware, specifically, can be used to protect certain routes or routes groups from unauthorized access.

============================OR========
you can use the built-in auth middleware to protect routes and controllers from unauthorized access. The auth middleware is added to routes or controllers that should only be accessible to authenticated users.

Middleware: Middleware are classes that handle HTTP requests and responses. They can be used to perform tasks such as authentication, validation, and rate limiting. In Laravel, you can create custom middleware and apply them to routes using the middleware option when defining the route.

Here's an example of how to use the built-in authentication middleware in Laravel 9:

  1. Run the command php artisan make:auth to create the necessary views and controllers for authentication.

  2. In the routes/web.php file, use the middleware method on a route group to apply the auth middleware to all routes within that group. For example

Image description

Route::middleware(['auth'])->group(function () {
    Route::get('/dashboard', 'DashboardController@index')->name('dashboard');
});
Enter fullscreen mode Exit fullscreen mode

============================OR==================================

Route::middleware(['auth'])->group(function () {
    Route::get('/dashboard', 'DashboardController@index');
});
Enter fullscreen mode Exit fullscreen mode

Image description

This example will only allow authenticated users to access the '/dashboard' route, which is handled by the 'DashboardController' controller's 'index' method.

You can also use the auth middleware on specific routes:

Route::get('/profile', 'ProfileController@index')->middleware('auth');
Enter fullscreen mode Exit fullscreen mode

Image description

3.In the controller, use the middleware property to apply the auth middleware.

class DashboardController extends Controller
{
    /**
     * Instantiate a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        return view('dashboard');
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)