Ad

Laravel Routes Not Working After Login

- 1 answer

I am new to Laravel and just started building my first app. I am using Laravel 5.2.5. I was following the laracast video in order to implement authentication. When I start the application for the first time, I can access /auth/register, /auth/login and /auth/logout. Register and Login work fine. Register creates an entry in my User table and /auth/login lets me login with that user. After successful login, I try to logout. When I try to access /auth/logout, I get an NotFoundHttpException. I get the same exception when I try to access /auth/login and /auth/register. At this point I can only access welcome and test pages. On the welcome page I am displaying the currently logged user and I can see that he is still logged in. I didn't change any code in the rest of the files.

Here is my routes.php code:

Route::group(['middleware' => ['web']], function () {
    Route::get('welcome', function () {
        return view('welcome');
    });
    Route::get('test','[email protected]');

    Route::get('auth/login', 'Auth\[email protected]');
    Route::post('auth/login', 'Auth\[email protected]');
    Route::get('auth/logout', 'Auth\[email protected]');

// Registration routes...
    Route::get('auth/register', 'Auth\[email protected]');
    Route::post('auth/register', 'Auth\[email protected]');
});

AuthenticationController:

<?php

namespace App\Http\Controllers\Auth;

use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;

class AuthController extends Controller
{  

    use AuthenticatesAndRegistersUsers, ThrottlesLogins;

    /**
     * Where to redirect users after login / registration.
     *
     * @var string
     */
    protected $redirectTo = '/welcome';

    /**
     * Create a new authentication controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest', ['except' => 'logout']);
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|max:255',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|confirmed|min:6',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
    }
}

login.blade.php:

<form method="POST" action="/auth/login">
    {!! csrf_field() !!}

    <div>
        Email
        <input type="email" name="email" value="{{ old('email') }}">
    </div>

    <div>
        Password
        <input type="password" name="password" id="password">
    </div>

    <div>
        <input type="checkbox" name="remember"> Remember Me
    </div>

    <div>
        <button type="submit">Login</button>
    </div>
</form>

register.blade.php:

<form method="POST" action="/auth/register">
    {!! csrf_field() !!}

    <div>
        Name
        <input type="text" name="name" value="{{ old('name') }}">
    </div>

    <div>
        Email
        <input type="email" name="email" value="{{ old('email') }}">
    </div>

    <div>
        Password
        <input type="password" name="password">
    </div>

    <div>
        Confirm Password
        <input type="password" name="password_confirmation">
    </div>

    <div>
        <button type="submit">Register</button>
    </div>
</form>

welcome.blade.php:

            <div class="title">Laravel 5</div>
            <div>{{\Auth::user()}}</div>
Ad

Answer

Long story short: It's because you don't have the '/' route registered.

Longer explanation: I'll first answer your NotFoundHttpException when you try to access /auth/login and /auth/register.

In your AuthController, you will see this line of code:

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

This bit of code basically ensures that only guests (or non-authenticated users) have access unless it comes to the logout method.

What is this "guest" middleware? If you look inside app/Http/Kernel.php, you will see this line of code:

'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,

The "guest" is basically an alias for the RedirectIfAuthenticated class. Inside that class, you will see this line of code:

if (Auth::guard($guard)->check()) {
    return redirect('/');
}

You see that if the user is already authenticated, they will be redirected to the '/' page. Since you don't have that route registered, you get the NotFoundHttpException. You can either register that route in your routes file or you can change the route inside your RedirectIfAuthenticated class.

Next, you are getting that same exception when you try to logout for the same reason. When you try to logout, it will trigger this bit of code:

public function logout()
{
    Auth::logout();

    return redirect(property_exists($this, 'redirectAfterLogout') ? $this->redirectAfterLogout : '/');
}

In other words, you will be redirected to the '/' page, which you don't have registered. If you want to redirect to another page rather than the '/' page, add this line of code to your AuthController.

protected $redirectAfterLogout = '/some-other-route';
Ad
source: stackoverflow.com
Ad