How to Set Up a Logout Laravel Breeze

Posted on

Laravel Breeze provides a simple authentication system that includes login, registration, and profile features. However, one common point of confusion is setting up the logout functionality, as Laravel requires a GET request for logging out, which can’t be accessed by directly navigating to /logout. This guide will help you configure the Logout Laravel Breeze route properly.

How to Set Up a Logout Laravel Breeze

Step 1: Define the Logout Route

Since Laravel Breeze uses the AuthenticatedSessionController for handling login and logout, we need to set up a logout route with a GET method to point to this controller’s destroy method. This is the method that Laravel Breeze uses to handle user session destruction.

Open your routes/web.php file and add the following line:

Route::middleware('auth')->group(function () {
    Route::get('/logout', [AuthenticatedSessionController::class, 'destroy'])->name('logout');
});

Explanation:

  • We’re defining a GET route for /logout.
  • This route points to the destroy method in the AuthenticatedSessionController.
  • The auth middleware ensures only authenticated users can access this route.
  • We assign the name logout to the route for easy reference.

Step 2: Create a Logout Button

For better user experience, you may want to style the logout button to match your application’s design. Here’s an example with some basic styling:

In your Blade view file, add:

<form method="GET" action="{{ route('logout') }}" style="display: inline;">
    @csrf
    <button type="submit" style="background: none; border: none; color: #007bff; cursor: pointer; padding: 0;">
        Logout
    </button>
</form>

Explanation:

  • This form uses the GET method and points to the /logout route using route('logout').
  • The @csrf directive is included to protect against cross-site request forgery.
  • When the form is submitted, it sends a GET request to the /logout route, triggering the destroy method in AuthenticatedSessionController.

Step 3: Testing the Logout Functionality

  1. Login to your application.
  2. Click the logout button you created to log out.
  3. You should be redirected to the / route (or another route as specified in the destroy method).

If everything is set up correctly, the user will be logged out, and the session data will be invalidated.