I am using Laravel 5.4 and trying to implement authentication system. I used php artisan command make:auth to setup it. I edited the views according to my layout. Now, when
I recommend you stick with Laravel auth routes in web.php: Auth::routes()
It will create the following route:
POST | logout | App\Http\Controllers\Auth\LoginController@logout
You will need to logout using a POST form. This way you will also need the CSRF token which is recommended.
<form method="POST" action="{{ route('logout') }}">
@csrf
<button type="submit">Logout</button>
</form>
You can use the following in your controller:
return redirect('login')->with(Auth::logout());
It's better and safer to add to your LoginController.php the following code, that runs only after the standard logout:
use AuthenticatesUsers;
protected function loggedOut(Request $request)
{
return redirect('/new/redirect/you/want');
}
In 5.5
adding
Route::get('logout', 'Auth\LoginController@logout');
to my routes file works fine.
if you are looking to do it via code on specific conditions, here is the solution worked for me. I have used in middleware to block certain users: these lines from below is the actual code to logout:
$auth = new LoginController();
$auth->logout($request);
Complete File:
namespace App\Http\Middleware;
use Closure;
use Auth;
use App\Http\Controllers\Auth\LoginController;
class ExcludeCustomers{
public function handle($request, Closure $next){
$user = Auth::guard()->user();
if( $user->role == 3 ) {
$auth = new LoginController();
$auth->logout($request);
header("Location: https://google.com");
die();
}
return $next($request);
}
}
If you used the auth scaffolding in 5.5 simply direct your href to:
{{ route('logout') }}
There is no need to alter any routes or controllers.