After login getting too many redirects error - laravel

Whenever I try to add a product to a wishlist I am redirected to a login page where I enter my credentials and after that it keeps reloading and this error appears.
Thereafter, when I return to home page and refresh I am logged in. But when I try to access a page directly which requires login, it works perfectly fine. This error has been appearing for sometime now, it was previously working fine.
routes:
Auth::routes();
Route::group(['middleware'=>'auth'],function (){
Route::get('/checkout','PageController#checkout')->name('checkout');
Route::post('/coupon','PageController#coupon')->name('coupon.check');
Route::post('/order', 'OrderController#store')->name('order.store');
Route::post('/orderinfo', 'OrderInfoController#store')->name('orderinfo.store');
Route::get('/invoice/{order}','PageController#invoice')->name('invoice');
Route::resource('/profile', 'ProfileController');
Route::get('/wishlist', 'WishlistController#index')->name('wishlist.index');
Route::get('/wishlist/{product_id}/remove', 'WishlistController#remove')->name('wishlist.remove');
Route::get('/wishlist/{product_id}', 'WishlistController#quick')->name('wishlist.quick');
Route::resource('/review', 'ReviewController');
Route::get('/orders', 'PageController#order')->name('orders');
Route::group(['middleware'=>'admin'],function () {
Route::resource('/admin/products', 'ProductController');
Route::resource('/admin/categories', 'CategoryController');
Route::resource('/admin/subcategories', 'SubcategoryController');
Route::resource('/admin/coupons', 'CouponController');
Route::resource('/admin/taxes', 'TaxController');
Route::resource('/admin/discounts', 'DiscountController');
Route::get('/admin/index', 'PageController#admin')->name('admin.index');
Route::post('/admin/ajax/category', 'PageController#ajax')->name('ajax.category');
Route::resource('/admin/users', 'UserController');
Route::resource('/admin/tracks', 'TrackController');
Route::get('/order', 'OrderController#index')->name('order.index');
Route::get('/order/{order}', 'OrderController#show')->name('order.show');
});
});
Route::get('/product/{product}','PageController#product')->name('product.view');
Route::get('/','PageController#index')->name('index');
Route::get('/about-us','PageController#about_us')->name('about_us');
Route::resource('/contact-us','ContactController');
Route::get('/shop','PageController#shop')->name('shop');
Route::get('/home', 'HomeController#index')->name('home');
Route::post('/cart', 'CartController#add')->name('cart.add');
Route::get('/cart{product}', 'CartController#quick')->name('cart.quick');
Route::get('/cart/show', 'CartController#show')->name('cart.show');
Route::patch('/cart/{product_id}', 'CartController#update')->name('cart.update');
Route::get('/cart/{product}/remove', 'CartController#remove')->name('cart.remove');
Route::get('/shop/filter/{subcategory_id}','PageController#filter')->name('filter.product');
Route::get('/shop/category/{category}','PageController#shop_2')->name('filter.categories');
Login Controller:
<?php
namespace App\Http\Controllers\Auth;
use App\Category;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function redirectTo()
{
}
public function showLoginForm()
{
$categories = Category::all();
$cart_items = session()->get('cart');
$sub_total = 0;
if (!empty($cart_items)) {
foreach ($cart_items as $item) {
$sub_total = ($item['price'] * $item['quantity']) + $sub_total;
}
}
return view('login', ['cart_items' => $cart_items, 'sub_total' => $sub_total,'categories'=>$categories]);
}
}
This is how I am sending get request and which gives error after login:
<a class="add-wishlist" title="wishlist" href="{{route('wishlist.quick',$product->id)}}"><i class="fa fa-heart"></i></a>
Wishlist Controller:
<?php
namespace App\Http\Controllers;
use App\Category;
use App\Helpers\helper;
use App\Product;
use App\Wishlist;
use Illuminate\Http\Request;
class WishlistController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
$categories= Category::all();
$cart_items = helper::cart_data();
$sub_total = helper::sub_total($cart_items);
$user_id = auth()->user()->id;
$wishlist = Wishlist::all()->where('user_id', '=', $user_id);
$products = [];
foreach ($wishlist as $list) {
$products[] = Product::find($list->product_id);
}
return view('wishlist', ['wishlist' => $wishlist, 'products' => $products,'sub_total'=>$sub_total,'categories'=>$categories,'cart_items'=>$cart_items]);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
$user_id = auth()->user()->id;
$check = Wishlist::all()->where('user_id', $user_id)->where('product_id', $request['product_id']);
if ($check->isEmpty()) {
Wishlist::create([
'user_id' => $user_id,
'product_id' => $request['product_id']
]);
}
return redirect()->back();
}
/**
* Display the specified resource.
*
* #param \App\Wishlist $wishlist
* #return \Illuminate\Http\Response
*/
public function show(Wishlist $wishlist)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Wishlist $wishlist
* #return \Illuminate\Http\Response
*/
public function edit(Wishlist $wishlist)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Wishlist $wishlist
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Wishlist $wishlist)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param \App\Wishlist $wishlist
* #return \Illuminate\Http\Response
*/
public function remove(Request $request)
{
//
$user_id = auth()->user()->id;
Wishlist::where('user_id', $user_id)->where('product_id', $request['product_id'])->delete();
return redirect()->back();
}
public function quick($product_id)
{
//
$user_id = auth()->user()->id;
$check = Wishlist::all()->where('user_id', $user_id)->where('product_id', $product_id);
if ($check->isEmpty()) {
Wishlist::create([
'user_id' => $user_id,
'product_id' => $product_id
]);
}
return redirect()->back();
}
}

Firstly, 419 error indicate an expired session. I notice you are using the session helper method session() inside showLoginForm(). You should be aware that if a user is logged out or his/her session expires then that user cannot access the data stored in that session as it will be wiped clean. Trying to access session data this way through showLoginForm is counter-intuitive as the user will most likely have been logged out or had an expired session before accessing the login form - except for the case where the user is accessing the login form for the first time. This could be a possible cause of the 419 errors.
You can remove the piece of code where you are trying to access the session data to any of your several controllers that require authentication. Then, you are sure that the user has a valid session before accessing session data.
However, to redirect users after a successful login Laravel uses either the $redirectTo variable or redirectTo() method of the LoginController. If the method is defined, it overrides the variable and if not, the variable is used.
From your LoginController, none of them is defined. Usually, the variable is set to redirect to the homepage - $redirectTo = '/home'. However, to meet your requirement of redirecting to the page that required the login, you must use the redirectTo() method.
You can achieve this by using the helper method url()->previous() within LoginController.php like this:
public static $previous;
public function showLoginForm() {
self::$previous = url()->previous();
// continue with your code.
}
public function redirectTo()
{
return self::$previous;
}
notice that I store the previous url when i first show the login form. after a successful login, this url should be available for me to redirect to.
UPDATE 1:
The problem route
Route::get('/cart{product}', 'CartController#quick')->name('cart.quick');
has a problem. You are missing a forward slash after /cart. You should notice this issue when you look at the generated url in the link. The correct form should be
Route::get('/cart/{product}', 'CartController#quick')->name('cart.quick');
UPDATE 2:
Since the route wishlist.quick is going through the auth middleware, do not use redirect()->back() for going back to the same page after user action with that route.
This is because, with the auth middleware in place, redirect()->back() is not always pointing to same location.
For instance, an unauthenticated user accessing the wishlist.quick route will be redirected to the login page. If login is successful the request continues to wishlist.quick route. Now, try to guess where the redirect()->back() inside WishlistController#quick is pointing to. Right! Surprisingly, it is pointing to the login page. So now the authenticated user completes his/her request with WishlistController#quick and is directed to the login page again. The login controller detects the user is authenticated and redirects the user to wherever he/she is coming from - WishlistController#quick. Again, there is redirect()->back() sending the user back again to the login page. You see the infinite redirect loop clearly in this funny scenario.
SOLUTION:
Change the line
return redirect()->back();
to
return $this->index();
Since WishlistController#quick doesn't return a view of its own, WishlistController#index is the best place to return to. Infact, you have to make this change for all routes that pass through a middleware and redirects the user back.
In other words, do not use redirect()->back() in a route that goes through middleware, if you really mean to go back to the same page.

A common issue with Laravel throwing a 419 error is because of a missing #csrf inside the form.
<form method="post" action="<some route>" >
#csrf
<input ...... />
</form>
If you are sending any data in a form, please ensure you have the above CSRF token.
If you do have this token, can you add the form in the main question?

Related

Laravel Login Controller - Direct to Admin or User Routes

I have a Laravel8 Project where I am doing everything from scratch so i can learn the system (newbie) - I have a LoginController with the code
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class LoginController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
// Show Login Page
return view('auth.login');
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
$this->validate($request, [
'email'=> 'required|email',
'password' => 'required',
]);
if (!auth()->attempt($request->only('email', 'password'), $request->remember)) {
return back()->with('status', 'Invalid Login Details' );
}
return redirect()->route('admin.dashboard');
}
I have the roles tables and pivot table set up but not sure how to amend the return redirect()->route('admin.dashboard'); to the correct code so depending if the user is an admin or a standard user it uses the correct route
You can give simple condition after login attempt success like below.
if (auth()->user()->role == 'admin') {
return redirect()->route('admin.dashboard');
}
return redirect()->route('user.dashboard');
As per your described question, you have a different table for assign roles to the user. So you have to create relation with roles table to identifies the role of the user.
You'll need to make sure to import the Auth facade at the top of the class. Next, let's check out the attempt method:
use Illuminate\Support\Facades\Auth;
...
public function store(Request $request) {
// ...
if (!auth()->attempt($request->only('email', 'password'), $request->remember)) {
return back()->with('status', 'Invalid Login Details' );
}
// Redirect to admin dashboard
return redirect()->intended('route.dashboard');
}
For more details read the Docs Manually Authenticating Users

Laravel pass GET parameters from register form to custom redirect URL

When a user signs up they land on the register page with some GET parameters. After they register I'd like to redirect them to the next page and keep these GET parameters.
In Auth\RegisterController I think I can use the method redirectTo as defined in the Illuminate\Foundation\Auth\RedirectsUsers trait.
But how can I achieve what I like using this method? Do I call it at the end of the create() method in the RegisterController like:
create()
{
// ...
$this-> redirectTo($request->get('param1'), $request->get('param2'))
}
and then define
protected function redirectTo($param1, $param2)
{
return redirect()->route('example?param1='.$param1.'&param2='.$param2);
}
I'm not sure where redirectTo() should go and if this is the right way to achieve this.
I recommend that you use the routes and then play on the status of the application with the session.
Or you can modify the value of $this->redirectTo in the authenticated which gives you in parameter an instance of Request and the registered user.
/**
* Register listener
*
* #param Reauest $request
* #param User $user
* #return mixed
*/
protected function registered(Request $request, $user)
{
$param1 = $request->get('param1');
$param2 = $request->get('param2');
$user->sendWelcomeNotification();
$this->redirectTo = 'example?param1='.$param1.'&param2='.$param2;
}

Conditionally redirect users after login in laravel backpack

I have some roles asigned to users. I would like to have a user redirected after login to different urls in order the role that user belongs to.
I have followed this post but it didn't work to me. I don't know if using backpack it would be different.
Best regards.
Edit.
This is the code in the login controller.
<?php
namespace Backpack\Base\app\Http\Controllers\Auth;
use Backpack\Base\app\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
class LoginController extends Controller{
protected $data = []; // the information we send to the view
protected $redirectTo = '/home';
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers {
logout as defaultLogout;
}
protected function authenticated(Request $request, $user){
/*if ( $user->isAdmin() ) {// do your margic here
return redirect('/home1');
}*/
return redirect('/myhome');
}
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$guard = backpack_guard_name();
$this->middleware("guest:$guard", ['except' => 'logout']);
// ----------------------------------
// Use the admin prefix in all routes
// ----------------------------------
// If not logged in redirect here.
$this->loginPath = property_exists($this, 'loginPath') ? $this->loginPath
: backpack_url('login');
// Redirect here after successful login.
$this->redirectTo = property_exists($this, 'redirectTo') ? $this->redirectTo
: backpack_url('dashboard');
// Redirect here after logout.
$this->redirectAfterLogout = property_exists($this, 'redirectAfterLogout') ? $this->redirectAfterLogout
: backpack_url();
}
/**
* Return custom username for authentication.
*
* #return string
*/
public function username()
{
return backpack_authentication_column();
}
/**
* Log the user out and redirect him to specific location.
*
* #param \Illuminate\Http\Request $request
*
* #return \Illuminate\Http\Response
*/
public function logout(Request $request)
{
// Do the default logout procedure
$this->guard()->logout();
// And redirect to custom location
return redirect($this->redirectAfterLogout);
}
/**
* Get the guard to be used during logout.
*
* #return \Illuminate\Contracts\Auth\StatefulGuard
*/
protected function guard()
{
return backpack_auth();
}
// -------------------------------------------------------
// Laravel overwrites for loading backpack views
// -------------------------------------------------------
/**
* Show the application login form.
*
* #return \Illuminate\Http\Response
*/
public function showLoginForm()
{
$this->data['title'] = trans('backpack::base.login'); // set the page title
$this->data['username'] = $this->username();
return view('backpack::auth.login', $this->data);
}
}
If I put this code in the path
vendor\backpack\base\src\app\Http\Controllers\Auth\LoginController.php
It works fine. But If I put the code in
app\Http\Controllers\Auth\LoginController.php
It does not work
I'm trying to extend the controller like this
use Backpack\Base\app\Http\Controllers\Auth\LoginController as OriginalLoginController;
class MyLoginController extends OriginalLoginController{
.....
}
To create a redirect in Laravel:
<?php
if($x){
return redirect()->route('routeName1', [$arr, $of, $params]);
}
else if($y){
return redirect()->route('routeName2', [$arr, $of, $params]);
}

Laravel middleware 'except' rule not working

I have a controller with the following in the constructor:
$this->middleware('guest', ['except' =>
[
'logout',
'auth/facebook',
'auth/facebook/callback',
'auth/facebook/unlink'
]
]);
The 'logout' rule (which is there by default) works perfectly but the other 3 rules I have added are ignored. The routes in routes.php look like this:
Route::group(['middleware' => ['web']],function(){
Route::auth();
// Facebook auth
Route::get('/auth/facebook', 'Auth\AuthController#redirectToFacebook')->name('facebook_auth');
Route::get('/auth/facebook/callback', 'Auth\AuthController#handleFacebookCallback')->name('facebook_callback');
Route::get('/auth/facebook/unlink', 'Auth\AuthController#handleFacebookUnlink')->name('facebook_unlink');
}
If I visit auth/facebook, auth/facebook/callback or auth/facebook/unlink whilst logged in I get denied by the middleware and thrown back to the homepage.
I've tried specifying the 'except' rules with proceeding /'s so they match the routes in routes.php exactly but it makes no difference. Any ideas why these rules are being ignored, whilst the default 'logout' rule is respected?
Cheers!
You need to pass the method's name instead of the URI.
<?php
namespace App\Http\Controllers;
class MyController extends Controller {
public function __construct() {
$this->middleware('guest', ['except' => [
'redirectToFacebook', 'handleFacebookCallback', 'handleFacebookUnlink'
]]);
}
}
Since Laravel 5.3, you can use fluent interface to define middlewares on controllers, which seems cleaner than using multidimensional arrays.
<?php
$this->middleware('guest')->except('redirectToFacebook', 'handleFacebookCallback', 'handleFacebookUnlink');
I solved this issue in my Middleware by adding this inExceptArray function. It's the same way VerifyCsrfToken handles the except array.
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class MyMiddleware
{
/**
* Routes that should skip handle.
*
* #var array
*/
protected $except = [
'/some/route',
];
/**
* Determine if the request has a URI that should pass through.
*
* #param Request $request
* #return bool
*/
protected function inExceptArray($request)
{
foreach ($this->except as $except) {
if ($except !== '/') {
$except = trim($except, '/');
}
if ($request->is($except)) {
return true;
}
}
return false;
}
/**
* Handle an incoming request.
*
* #param Request $request
* #param Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
// check user authed or API Key
if (!$this->inExceptArray($request)) {
// Process middleware checks and return if failed...
if (true) {
// Middleware failed, send back response
return response()->json([
'error' => true,
'Message' => 'Failed Middleware check'
]);
}
}
// Middleware passed or in Except array
return $next($request);
}
}
If you are trying to follow the Laravel Documentation, an alternative solution to this is suggested by adding routes to the $except variable in the /Http/Middleware/VerifyCsrfToken.php file. The documentation says to add them like this:
'route/*'
But I found the only way to get it to work is by putting the routes to ignore like this:
'/route'
When assigning middleware to a group of routes, you may occasionally need to prevent the middleware from being applied to an individual route within the group. You may accomplish this using the withoutMiddleware method:
use App\Http\Middleware\CheckAge;
Route::middleware([CheckAge::class])->group(function () {
Route::get('/', function () {
//
});
Route::get('admin/profile', function () {
//
})->withoutMiddleware([CheckAge::class]);
});
for more information read documentation laravel middleware
Use this function in your Controller:
public function __construct()
{
$this->middleware(['auth' => 'verified'])->except("page_name_1", "page_name_2", "page_name_3");
}
*replace page_name_1/2/3 with yours.
For me it's working fine.
I have this solved, and here's what I am doing. Aso, I just realized this is very similar to what cmac did in his answer.
api.php
Route::group(['middleware' => 'auth'], function () {
Route::get('/user', 'Auth\UserController#me')->name('me');
Route::post('logout', 'Auth\LoginController#logout')->name('logout');
});
LoginController.php
class LoginController extends Controller
{
use AuthenticatesUsers, ThrottlesLogins;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
// ...
/**
* If the user's session is expired, the auth token is already invalidated,
* so we just return success to the client.
*
* This solves the edge case where the user clicks the Logout button as their first
* interaction in a stale session, and allows a clean redirect to the login page.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function logout(Request $request)
{
$user = $this->guard()->user();
if ($user) {
$this->guard()->logout();
JWTAuth::invalidate();
}
return response()->json(['success' => 'Logged out.'], 200);
}
}
Authenticate.php
class Authenticate extends Middleware
{
/**
* Exclude these routes from authentication check.
*
* Note: `$request->is('api/fragment*')` https://laravel.com/docs/7.x/requests
*
* #var array
*/
protected $except = [
'api/logout',
];
/**
* Ensure the user is authenticated.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
try {
foreach ($this->except as $excluded_route) {
if ($request->path() === $excluded_route) {
\Log::debug("Skipping $excluded_route from auth check...");
return $next($request);
}
}
// code below here requires 'auth'
{ catch ($e) {
// ...
}
}
I over-engineered it slightly. Today I only need an exemption on /api/logout, but I set the logic up to quickly add more routes. If you research the VerifyCsrfToken middleware, you'll see it takes a form like this:
protected $except = [
'api/logout',
'api/foobars*',
'stripe/poop',
'https://www.external.com/yolo',
];
That's why I put that "note" in my doc above there. $request->path() === $excluded_route will probably not match api/foobars*, but $request->is('api/foobars*') should. Additionally, a person might be able to use something like $request->url() === $excluded_route to match http://www.external.com/yolo.
You should pass the function name to 'except'.
Here's an example from one of my projects:
$this->middleware('IsAdminOrSupport', ['except' => [
'ProductsByShopPage'
]
]);
This means the middleware 'IsAdminOrSupport' is applied to all methods of this controller except for the method 'ProductByShopPage'.

Make session expiration redirect back to login?

When user logs in and is authenticated, I use Auth::user()->username; to show username of user on dashboard. However, for some reason when session expires the class Auth doesn't seem to work and dashboard page throws error as trying to get property of non-object for Auth::user()->username;. How can I redirect the user back to the login page when he clicks any link or refreshes the page after the session has expired?
I tried the Authenticate.php middleware but it always redirects back to login page,whatever you put the credentials either correct or incorrect.However,when I don't use this middleware it logins the user.Am I missing something?
Route.php
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
/*
Actions Handled By Resource Controller
Verb Path Action Route Name
GET /photo index photo.index
GET /photo/create create photo.create
POST /photo store photo.store
GET /photo/{photo} show photo.show
GET /photo/{photo}/edit edit photo.edit
PUT/PATCH /photo/{photo} update photo.update
DELETE /photo/{photo} destroy photo.destroy
Adding Additional Routes To Resource Controllers
If it becomes necessary to add additional routes to a resource controller beyond the default resource routes, you should define those routes before your call to Route::resource:
Route::get('photos/popular', 'PhotoController#method');
Route::resource('photos', 'PhotoController');
*/
// Display all SQL executed in Eloquent
// Event::listen('illuminate.query', function($query)
// {
// var_dump($query);
// });
define('ADMIN','admin');
define('SITE','site');
Route::group(['namespace' => ADMIN], function () {
Route::get('/','UserController#showLogin');
});
////////////////////////////////////Routes for backend///////////////////////////////////////////////////
Route::group(['prefix' => ADMIN,'middleware' => 'auth'], function () {
Route::group(['namespace' => ADMIN], function () {
//Route::get('/','EshopController#products');
//sumit routes for user registration
//Route::resource('users','UserController');
Route::get('/users/destroy/{id}','UserController#destroy');
Route::get('UserProf','UserController#userProf');
Route::get('users','UserController#index');
Route::get('/users/create','UserController#create');
Route::get('/users/adminEdit/{id}','UserController#adminEdit');
Route::post('/users/adminUpdate','UserController#adminUpdate');
Route::post('/users/store','UserController#store');
Route::get('/users/edit/{id}','UserController#edit');
Route::post('/users/update/{id}','UserController#update');
//airlines route
Route::get('airlines','AirlinesController#index');
Route::get('/airlines/create','AirlinesController#create');
Route::post('/airlines/store','AirlinesController#store');
Route::get('/airlines/edit/{id}','AirlinesController#edit');
Route::post('/airlines/update','AirlinesController#update');
Route::get('/airlines/destroy/{id}','AirlinesController#destroy');
//end sumit routes
//flight routes
Route::get('flights','FlightController#index');
Route::get('showFlightBook','FlightController#showFlightBook');
Route::get('flights/create','FlightController#create');
Route::post('flights/store','FlightController#store');
Route::get('flights/book','FlightController#book');
Route::get('flights/edit/{id}','FlightController#edit');
Route::post('flights/update','FlightController#update');
Route::get('flights/destroy/{id}','FlightController#destroy');
//Route::resource('flight','FlightController');
//hotels route
Route::get('hotels','HotelsController#index');
Route::get('/hotels/create','HotelsController#create');
Route::post('/hotels/store','HotelsController#store');
Route::get('/hotels/edit/{id}','HotelsController#edit');
Route::post('/hotels/update','HotelsController#update');
Route::get('/hotels/destroy/{id}','HotelsController#destroy');
//end sumit routes
//book-hotel routes
Route::get('hotel-book','HotelBookController#index');
Route::get('showHotelBook','HotelBookController#showHotelBook');
Route::get('hotel-book/create','HotelBookController#create');
Route::post('hotel-book/store','HotelBookController#store');
Route::get('hotel-book/book','HotelBookController#book');
Route::get('hotel-book/edit/{id}','HotelBookController#edit');
Route::post('hotel-book/update','HotelBookController#update');
Route::get('hotel-book/destroy/{id}','HotelBookController#destroy');
//Route::resource('hotel','HotelController');
//close flight routes
//for admin login
//Route::get('initlogin','UserController#lgnPage');
Route::get('login','UserController#showLogin');
// Route::get('privilegeLogin','UserController#privilegeLogin');
// Route::post('privilegeCheck','UserController#privilegeCheck');
Route::post('login','UserController#doLogin');
Route::get('/dashboard','DashController#index');
Route::get('logout','UserController#doLogout');
//user login
//Route::get('userLogin','UserController#showUserLogin');
//Route::post('userLogin','UserController#doUserLogin');
Route::get('/userDashboard','DashController#userIndex');
Route::get('Logout','UserController#doUserLogout');
//password reset
Route::get('forget-pass','UserController#showReset');
//Route::get('home', 'PassResetEmailController#index');
});
});
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]);
Authenticate.php:
<?php namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Guard;
class Authenticate {
/**
* The Guard implementation.
*
* #var Guard
*/
protected $auth;
/**
* Create a new filter instance.
*
* #param Guard $auth
* #return void
*/
public function __construct(Guard $auth)
{
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if ($this->auth->guest())
{
if ($request->ajax())
{
return response('Unauthorized.', 401);
}
else
{
// return redirect()->guest('auth/login');
return redirect()->guest('/');
}
}
return $next($request);
}
}
All you have to do is just put this constructor at the top of the controller for your dashboard. It seems Laravel has a middleware that handles this already. At least I can confirm from 5.4 and up.
public function __construct()
{
$this->middleware('auth');
}
If the session expires then you can redirect to log in like as
open this file app/Exceptions/Handler.php add this code
public function render($request, Exception $exception)
{
if ($exception instanceof \Illuminate\Session\TokenMismatchException) {
return redirect('/login');
}
return parent::render($request, $exception);
}
If you want a middleware to be run during every HTTP request to your application, simply list the middleware class in the $middleware property of your app/Http/Kernel.php class.
So, to protect every route from being accessed without authentication do this
protected $middleware = [
'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
'Illuminate\Cookie\Middleware\EncryptCookies',
'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
'Illuminate\Session\Middleware\StartSession',
'Illuminate\View\Middleware\ShareErrorsFromSession',
'App\Http\Middleware\VerifyCsrfToken',
'App\Http\Middleware\Authenticate',// add this line according to your namespace
];
it will redirect the user if not logged in. UPDATE Keep in mind that adding auth middleware as global will create redirect loop so avoid it.
Or if you want specific routes to be protected then attach the middleware auth to that route
Route::get('admin/profile', ['middleware' => 'auth', function () {
//
}]);
I think you are not attaching the auth middleware to your routes.
Create a middleware like this
<?php namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Guard;
class Authenticate
{
/**
* The Guard implementation.
*
* #var Guard
*/
protected $auth;
/**
* Create a new filter instance.
*
* #param Guard $auth
* #return void
*/
public function __construct(Guard $auth)
{
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if ($this->auth->guest()) {
if ($request->ajax()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('login');
}
}
return $next($request);
}
}
Then Group the routes and protect them like this
Route::group(['middleware' => 'auth'], function()
{
Route::get();
Route::get();
Route::get();
Route::get();
}
Offcourse, in the routes you have to specify your links etc, it will only allow the user when he is authenticated and if not then login page will be shown
To make session redirect to your login just add ->middleware('auth') in your router files as shown below I am using laravel 5.3
Ex:
Route::post('controllerName','folderName\fileName#fnNmae')->middleware('auth');
Or visit https://laravel.com/docs/5.3/authentication

Resources