Search code examples
phplaravellaravel-bladelaravel-authentication

How to redirect non-authenticated users to login view


I'm making an application which requires a user and password for access. Every user should face the login view. Currently, writing the URL manually, I can access all the routes without login. What I want is to redirect every unauthenticated user to the login view, so that they can't see anything else until they log in.

LoginController

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{
    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    public function redirectTo() {
        $isAuth = Auth::check();

        if ($isAuth) {
            return redirect('dashboard');
        } else {
            return redirect('login');
        }
    }

    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    public function logout(Request $request) 
    {
        Auth::logout();

        return redirect('/login');
    }
}

Routes

<?php

Route::get('/', function () {
    return view('home');
});

Route::resource('project','ProjectController');
Route::resource('client','ClientController');
Route::resource('task','TaskController');
Route::resource('people','PeopleController');

Route::get('/login', function () {
    return view('login');
});

Route::get('logout', '\App\Http\Controllers\Auth\LoginController@logout');

Auth::routes();

Route::get('/dashboard', 'DashboardController@index');

Solution

  • You should move your Auth::routes() before your first route

     <?php
    
    Auth::routes()
    
    Route::get('/', function () {
         return view('home');
     });
    

    And use auth middleware in your controllers where you want only authenticated user.

    public function __construct()
    {
        $this->middleware('auth');
    }