How to log out and redirect to the login page in Laravel?
In this tutorial, today we will learn How to log out and redirect to the login page in Laravel? Laravel Auth is a Complete Build with Email Registration Verification, Admin restricted user management system, Social Authentication, and User Roles and Permissions. Laravel auth Built on Bootstrap 4. in this post, you will learn how to custom user logout and redirect to the login page.
Also read: Laravel Authentication Logout Code Example
Sometimes users get the below error and we will solve this error:
NotFoundHttpException in RouteCollection.php line 161:
Example
First open App\Http\Controllers\Auth\LoginController.php
and insert the below code:
<?php #App\Http\Controllers\Auth\LoginController.php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use App\Providers\RouteServiceProvider; use Illuminate\Foundation\Auth\AuthenticatesUsers; use Illuminate\Http\Request; use Auth; //added class LoginController extends Controller { use AuthenticatesUsers; protected $redirectTo = '/admin'; public function __construct() { $this->middleware('guest')->except('logout'); } /* added */ public function logout(Request $request) { Auth::logout(); return redirect('/login'); } }
Now, open routes\web.php
and add the below code:
Also read: How to login with username or email in Laravel authentication
#routes\web.php Route::get('logout', '\App\Http\Controllers\Auth\LoginController@logout');
And Last, open resources\views\layouts\app.blade.php
and put the below code:
#resources\views\layouts\app.blade.php <a class="dropdown-item" href="{{ route('logout') }}" onclick="event.preventDefault(); document.getElementById('logout-form').submit();"> {{ __('Logout') }} </a> <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;"> @csrf </form>