I can't logout with laravel - php

I'm working on my first laravel project in which I made an admin panel to make admin able to controller the website. I tried to login admin into dashboard and everything was fine, when I tried to log him out nothing works and the page was just reloading and redirect back.
Here is my logout button:
<a class="navbar-brand btn btn-primary btn-lg"
href="{{route('admin.logout'))}}"> log out</a>
My route:
Route::get('logout', 'LoginController#logout')->name('admin.logout');
And my controller:
use Illuminate\support\Facades\Auth;
public function logout(Request $request){
Auth::logout();
return redirect()->route('get.admin.login')
->with(['success'=>'logged out successfully']);
}
I used Auth::logout(); method from laravel official documentation, however it didn't work.
I hope I can find help.

as your using Auth::logout()inside that function
public function logout(Request $request) {
Auth::logout();
return redirect('/login');
}
here Auth:: will be null
so apply middleware to get Auth instance and then you can logout
Route::get('logout', 'LoginController#logout')->name('admin.logout')->middleware('auth');

You can use the following in your controller:
return redirect('login')->with(Auth::logout());

You can use below code, for logout the admin.
Auth::logout();
return redirect('/login');

Related

Laravel Logout functionality not working?

In laravel 5.7 Logout functionality not working when im going to click logout button it show me this error
/var/www/html/orderManager/vendor/auth0/login/src/Auth0/Login/Auth0Service.php
$this->authApi = new Authentication($this->auth0Config['domain'],
$this->auth0Config['client_id']);
"Undefined index: domain"
web.php
Route::get('logout', 'HomeController#logout');
HomeController.php
public function logout() {
Auth::logout();
Session::flush();
return redirect('/login');
}
i remove this
"auth0/login": "~5.0"
from composer.json and update composer and its working..
In case you are doing a custom logout yourself, you can change your logout method to look like this
public function logout() {
auth()->logout();
return redirect('/login');
}
Then remove the auth0 package and try running composer update

how to Implement logout functionality in laravel

without login If I give any URL's in the admin panel it is opening. How to solve it?
while login I am using,
$request->session()->put('userId', $user->userId);
In logout I am using,
$request->session()->forget('userId');
Route file,
Route::get('/addModule', function () {
return view('addModule');
});
How can I redirect to login screen. while am calling any admin panel URL's.
Just write this code in routes.php
Route::get('logout', function(Request $request) {
Auth::logout();
return redirect('/login');
});
Remember to import Auth class

customize redirection logged in user on /login route - laravel

I have a laravel application
login page is in route /login
there is a logged in user and clicks on a login button (or basically open URL /login)
application redirects the user to /home but I want to be redirected to /dashboard
I changed the redirect fields in Auth controllers to /dashboard. results when a user signs in, application redirects him to /dashboard
but what about a logged in user?
I use laravel 5.4, thank you for helping
You should use the RedirectIfAuthenticated middleware that is supplied with Laravel located in App\Http\Middleware\RedirectIfAuthenticated.
Then, in the following block, make sure it's set to /dashboard.
if (Auth::guard($guard)->check()) {
return redirect('/dashboard');
}
Then add the middleware to your login route by either wrapping it in a group:
Route::group(['middleware' => 'guest'], function(){
//Auth routes for non-authenticated users
});
Or you can do it on the route directly:
->middleware('guest');
Goto login controller which is located in
app->Http->Auth->LoginController
Set
protected $redirectTo = '/dashboard'
Hope it works.
Source : https://laravel.com/docs/5.4/authentication#included-authenticating
Since you want to redirect logged in user you can override showLoginForm() method in LoginController like this:
public function showLoginForm()
{
if (auth()->check()) {
return redirect('/dashboard');
}
return view('auth.login');
}
But I guess a better way to solve the problem could be just hiding login button or link from logged in users:
#if (auth()->guest())
{{-- Show register and login links --}}
#endif

How to logout and redirect to login page using Laravel 5.4?

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 am trying to logout it throwing me this error
NotFoundHttpException in RouteCollection.php line 161:
could any one help me how to logout?
In your web.php (routes):
add:
Route::get('logout', '\App\Http\Controllers\Auth\LoginController#logout');
In your LoginController.php
add:
public function logout(Request $request) {
Auth::logout();
return redirect('/login');
}
Also, in the top of LoginController.php, after namespace
add:
use Auth;
Now, you are able to logout using yourdomain.com/logout URL or if you have created logout button, add href to /logout
Well even if what suggest by #Tauras just works I don't think it's the correct way to deal with this.
You said you have run php artisan make:auth which should have also inserted Auth::routes(); in your routes/web.php routing files. Which comes with default logout route already defined and is named logout.
You can see it here on GitHub, but I will also report the code here for simplicity:
/**
* Register the typical authentication routes for an application.
*
* #return void
*/
public function auth()
{
// Authentication Routes...
$this->get('login', 'Auth\LoginController#showLoginForm')->name('login');
$this->post('login', 'Auth\LoginController#login');
$this->post('logout', 'Auth\LoginController#logout')->name('logout');
// Registration Routes...
$this->get('register', 'Auth\RegisterController#showRegistrationForm')->name('register');
$this->post('register', 'Auth\RegisterController#register');
// Password Reset Routes...
$this->get('password/reset', 'Auth\ForgotPasswordController#showLinkRequestForm')->name('password.request');
$this->post('password/email', 'Auth\ForgotPasswordController#sendResetLinkEmail')->name('password.email');
$this->get('password/reset/{token}', 'Auth\ResetPasswordController#showResetForm')->name('password.reset');
$this->post('password/reset', 'Auth\ResetPasswordController#reset');
}
Then again please note that logout requires POST as HTTP request method. There are many valid reason behind this, but just to mention one very important is that in this way you can prevent cross-site request forgery.
So according to what I have just pointed out a correct way to implement this could be just this:
<a href="{{ route('logout') }}" onclick="event.preventDefault(); document.getElementById('frm-logout').submit();">
Logout
</a>
<form id="frm-logout" action="{{ route('logout') }}" method="POST" style="display: none;">
{{ csrf_field() }}
</form>
Finally note that I have inserted laravel out of the box ready function {{ csrf_field() }}!
You can use the following in your controller:
return redirect('login')->with(Auth::logout());
Best way for Laravel 5.8
100% worked
Add this function inside your Auth\LoginController.php
use Illuminate\Http\Request;
And also add this
public function logout(Request $request)
{
$this->guard()->logout();
$request->session()->invalidate();
return $this->loggedOut($request) ?: redirect('/login');
}
here is another way to do it by calling Auth::logout() in route
Route::get('/logout', function(){
Auth::logout();
return Redirect::to('login');
});
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>
In Laravel 6.2
Add the following route to : web.php
Route::post('logout', 'Auth\LoginController#logout')->name('logout');
Using Achor tag with logout using a POST form. This way you will also need the CSRF token.
<a class="log-out-btn" href="#" onclick="event.preventDefault();document.getElementById('logout-form').submit();"> Logout </a>
<form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
{{ csrf_field() }}
</form>
In 5.5
adding
Route::get('logout', 'Auth\LoginController#logout');
to my routes file works fine.
I know this question was asked for old version of laravel. I want to share my solution for Laravel 8.65 version.
In AuthenticatedSessionControler update destroy function like this.
public function destroy(Request $request)
{
Auth::guard('web')->logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return redirect('/admin');
}
update your last line from return redirect('/') to return redirect('/admin');
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.
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 Laravel 9
go to routes directory open web.php and write logout route:
use App\Http\Controllers\Auth\LoginController;
Route::get('logout', [LoginController::class,'logout']);
From blade add logout URL
<a class="dropdown-item" href={{route('logout')}}>Logout</a>
Notice
logout function will redirect to home page /
If you want to redirect to login page you should override on logout function in App\Http\Controllers\Auth\LoginController.php
public function logout(){
return redirect('login')->with(Auth::logout());
}
Just in case someone is interested on this topic for Laravel 8 or 9.
As you can read on the Laravel documentation on https://laravel.com/docs/9.x/authentication#logging-out
In addition to Auth::logout(), you will need to invalidate the user's session and regenerate their CSRF token:
public function logout(Request $request)
{
Auth::logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return redirect('/');
}
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);
}
}

Laravel logout not working

I'm trying simple logout functionality in laravel 5.2 but don't really understand where am I wrong. It would be great is someone can help.
here's Route
Route::get('logout', 'loginController#getLogout');
loginController getLogout method:
public function getLogout()
{
//$this->auth->logout();
Session::flush();
Auth::logout();
return redirect('/');
}
link in view that uses this function:
Logout
session store code:
$request->session()->put('name', $username['name']);
AuthController constructor:
public function __construct()
{
$this->middleware('guest', ['except' => ['logout', 'getLogout']]);
}
When user clicks on the logout link, it does redirect to root page but doesn't really destroy session or logout. It isn't requiring login to view pages (which it should).
I too had the same problem and i have rectified by Method 1 and i had reference using Method 2.
Method 1:
Route::get('auth/logout', 'Auth\AuthController#logout');
Or Method 2:
or in AuthController constructor add
public function __construct()
{
$this->middleware('guest', ['except' => ['logout', 'getLogout']]);
}
Hope so this will clear up your Error. I had the same problem and i did like this alone
Session Destroy must be used like this
Session::forget('name');
$request->session()->flush(); // in your Controller
Try to change the route in routes.php with this:
Route::get('logout', 'Auth\AuthController#logout');
And for the logout route I use:
{{ url('/logout') }}
Normally this works, if you need to use a different controller for something especial, try to use the:
$request->session()->flush()
in the controller.
Following the Laravel 5.2 documentation -> https://laravel.com/docs/5.2/session.
Other approximation, try to modify the order in your controller, maybe it will work. According to the doc, Auth:logout() will clean all user auth data, then you can clean the other session data.
public function getLogout()
{
//$this->auth->logout();
Auth::logout();
Session::flush();
return redirect('/');
}

Categories