How to logout from any function outside a controller action in Laravel 5.5 - laravel-5

I have been trying to log out using :
Route::get('/myland',function(){
Auth::logout();
Session::flush();
});
But the user is not being logged out. In my scenario I am obliged to logout that way without using controller I don't know what I am missing.

In AuthController/loginController constructor add below code
public function __construct()
{
$this->middleware('guest', ['except' => ['logout', 'getLogout']]);
}
or
Route::get('/myland', function(){
Auth::logout();
return redirect('/');
});

Related

Call to a member function tokens() on null on Laravel Sanctum

I get this error when i am trying to logout the user
public function logout(Request $request)
{
$request->user()->tokens()->delete();
}
You need to include the API route inner the Sanctum Auth middleware like below:
Route::group(['middleware' => ['auth:sanctum']], function() {
Route::post('logout', [AuthController::class, 'logout']);
});
Auth::user()->token() is only valid by passing the Sanctum middleware.
Check this #1
Check this #2
This worked for me, Change this code in your Controller.php to,
public function logout(Request $request){
Auth::user()->tokens()->delete();
return [
'message' => 'logged out'
];
}
And make sure your Route POST request is protected in api.php, change the code to below
Route::post('/logout', [AuthController::class, 'logout'])->middleware('auth:sanctum');
use token() instead of tokens()
$request->user()->token()->delete();
Or you can use it as below.
Auth::user()->tokens->each(function($token, $key) {
$token->delete();
});
by using revoke
$user = $request->user();
foreach ($user->tokens as $token) {
$token->revoke();
}

Laravel 5.4 redirect to specific page if user is not authenticated using middleware

I want to redirect user, if not authenticated, to my index page (which is the login page)
Can't seem to make it work and i really got confused with the routing.
HomeController
class HomeController extends Controller
{
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return redirect()->guest('/');
}
}
Routing
// Index
Route::get('/', [
'as' => 'index',
'uses' => 'UserController#index'
]);
UserController
The routing as you see redirects to a User Controller at index function, which is the below :
*has __construct() so it uses the middleware 'auth'.
public function __construct()
{
$this->middleware('auth');
}
public function index(){
// If user is logged
if(Auth::check()) {
// If user has NOT submitted information form redirect there, otherwise to categories
if(!Auth::user()->submitted_information)
return redirect()->route('information');
else
return redirect()->route('categories');
}
else
return view('index', ['body_class' => 'template-home']);
}
Handler.php
And the unauthenticated function inside middleware of auth (Exceptions/Handler.php)
protected function unauthenticated($request, AuthenticationException $exception)
{
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401);
}
return redirect()->route('index');
}
The error i get right now is the below :
InvalidArgumentException in UrlGenerator.php line 304:
Route [index] not defined.
This error happens because of the line of
return redirect()->route('index'); in the above unauthenticated function.
What am i missing here? If you need any more information please feel free to ask.
EDIT : Until now, if i remove from UserController the __construct() method, and insert in web.php to all the routes what middleware to use, it works.
For example
Route::get('/categories', [
'as' => 'categories',
'uses' => 'UserController#showCategories'
])->middleware('auth');
But i am trying to find, without specifying there what middleware to use, to use it automatically.
Build your route like below code:
Route::group(['middleware' => ['auth']], function() {
// uses 'auth' middleware
Route::resource('blog','BlogController');
});
Route::get('/mypage', 'HomeController#mypage');
Open your middleware class named RedirectIfAuthenticated and then in handle fucntion
you write below code:
if (!Auth::check()) {
return redirect('/mypage'); // redirect to your specific page which is public for all
}
Hope it will work for you.
Your route should be like
// Index
Route::get('/','UserController#index')->name('index);
see here for more about routing.
Try
Route::get('/','UserController#index',['middleware'=>'auth'])->name('index);

Removing a route from Auth::routes()

I have these routes:
Auth::routes();
Route::get('/home', 'LibraryController#home');
Route::get('/', 'LibraryController#index');
Auth::routes() is generated by the command php artisan make::auth. But, i don't want the index page to be under auth middleware group, the third route in the above list.
Here is the controller methods. index() is for everyone and home() for authenticated users.
public function index()
{
return view('index');
}
public function home()
{
return view('home')->with('message','Logged in!');
}
the login users is redirected to home url:
protected $redirectTo = '/home';
But whenever i run the third route the login page appears. so, how can i remove that route from auth middleware group.
In your LibraryController before index where your controllers start you need to write
public function __construct()
{
$this->middleware('auth', ['except' => ['index']]);
}
Now every user will be able to go to index method without authentication
Documentation Reference https://laravel.com/docs/5.0/controllers#controller-middleware
Since Laravel 7.7 you can use excluded_middleware property eg:
Route::group([
'excluded_middleware' => ['auth'],
], function () {
Route::get('/home', 'LibraryController#home');
Route::get('/', 'LibraryController#index');
});

Laravel authentication for register

laravel authentication model
Is there any possible to make /register only you logged
How to make it with : (Auth::check()) ??
By default in construct of \app\Http\Controllers\Auth\AuthController.php we have middleware guest for all except logout:
public function __construct()
{
$this->middleware('guest', ['except' => [
'logout',
]
]);
}
Middleware guest link for:
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
And use handle method:
public function handle($request, Closure $next)
{
if ($this->auth->check())
{
return new RedirectResponse(url('/'));
}
return $next($request);
}
It's mean that everybody who try access all Auth method except logout will be redirected to main page.
You should look at middleware if your are at laravel 5: https://laravel.com/docs/master/middleware
And filters for laravel 4: https://laravel.com/docs/4.2/routing

Lravel 5.2 session::forget() and session::flush() not working

i have just make a sub authentication Middleware in my Laravel 5.2 application which use Laravel session to store data.
I can put my data to Laravel session
But when i want to delete that variable form session it working for only that request when page redirect or someone reload the page that variable still exists.
In My controller File
class SubmissionController extends Controller
{
public function login(Request $request){
if($request->session()->has('submission')) return redirect('/submission-directory');
return view('submission.login');
}
public function dologin(Request $request){
if(!$request->get('password') == "reader") return redirect('/submission-directory/login')->withErrors('errors.wrong-password');
Session::put('submission','yes');
$redirect = $request->session()->pull('submission_redirect','/submission-directory');
return redirect($redirect);
}
public function index(Request $request){
dump($request->session()->all());
$request->session()->forget('submission');
dump($request->session()->all());
die('coming here');
}
}
but when I reload the page You can session is still exists..
Notice :: I have put all the routs in web Middleware group
Route.php
Route::group(['middleware' => 'web'], function () {
Route::group(['prefix'=>'/submission-directory'],function(){
Route::get('/login','submissionController#login');
Route::post('/login',['as'=>'submission.login','uses'=>'SubmissionController#doLogin']);
Route::group(['middleware'=>'submission'],function(){
Route::get('/','SubmissionController#index');
});
});
Try this
IN Controller :
use Session;
public function index(Request $request)
{
dump(Session::all());
Session::forget('submission');
print_r((Session::all());
die;
}

Resources