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

laravelredirectrouting

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.

Best Answer

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.

Related Topic