Route [login] not defined

Trying to play with Laravel today for the first time. I am getting the following error when I attempt to visit localhost/project/public:

InvalidArgumentException
Route [login] not defined.

app/routes.php:

<?php

Route::get('/', 'HomeController@redirect');
Route::get('login', 'LoginController@show');
Route::post('login', 'LoginController@do');
Route::get('dashboard', 'DashboardController@show');

app/controllers/HomeController.php:

<?php

class HomeController extends Controller {

    public function redirect()
    {
        if (Auth::check()) 
            return Redirect::route('dashboard');

        return Redirect::route('login');
    }

}

app/controllers/LoginContoller.php:

<?php

class LoginController extends Controller {

    public function show()
    {
        if (Auth::check()) 
            return Redirect::route('dashboard');

        return View::make('login');
    }

    public function do()
    {
        // do login
    }

}

app/controllers/DashboardController.php:

<?php

class DashboardController extends Controller {

    public function show()
    {
        if (Auth::guest()) 
            return Redirect::route('login');

        return View::make('dashboard');
    }

}

Why am I getting this error?


You're trying to redirect to a named route whose name is login, but you have no routes with that name:

Route::post('login', [ 'as' => 'login', 'uses' => 'LoginController@do']);

The 'as' portion of the second parameter defines the name of the route. The first string parameter defines its route.


Try to add this at Header of your request: Accept=application/json postman or insomnia add header


In app\Exceptions\Handler.php

protected function unauthenticated($request, AuthenticationException $exception)
{
    if ($request->expectsJson()) {
        return response()->json(['error' => 'Unauthenticated.'], 401);
    }

    return redirect()->guest(route('auth.login'));
}

You need to add the following line to your web.php routes file:

Auth::routes();

In case you have custom auth routes, make sure you /login route has 'as' => 'login'


Laravel has introduced Named Routes in Laravel 4.2.

WHAT IS NAMED ROUTES?

Named Routes allows you to give names to your router path. Hence using the name we can call the routes in required file.


HOW TO CREATE NAMED ROUTES?

Named Routes created in two different way : as and name()

METHOD 1:

Route::get('about',array('as'=>'about-as',function()
    {
            return view('about');
     }
));

METHOD 2:

 Route::get('about',function()
{
 return view('about');
})->name('about-as');

How we use in views?

<a href="{{ URL::route("about-as") }}">about-as</a>

Hence laravel 'middleware'=>'auth' has already predefined for redirect as login page if user has not yet logged in.Hence we should use as keyword

    Route::get('login',array('as'=>'login',function(){
    return view('login');
}));