Route [login] not defined

PhpLaravel

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

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.

Solution 2 - Php

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

Solution 3 - Php

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'));
}

Solution 4 - Php

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');
}));

Solution 5 - Php

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'

Solution 6 - Php

In case of API , or let say while implementing JWT . JWT middleware throws this exception when it couldn't find the token and will try to redirect to the log in route. Since it couldn't find any log in route specified it throws this exception . You can change the route in "app\Exceptions\Handler.php"

use Illuminate\Auth\AuthenticationException;

protected function unauthenticated($request, AuthenticationException $exception){
    	return $request->expectsJson()
        	 ? response()->json(['message' => $exception->getMessage()], 401)
         	: redirect()->guest(route('ROUTENAME'));
}

Solution 7 - Php

Am late to the party. if your expectation is some sort of json returned other than being redirected, then edit the exception handler so do just that.

Go to go to App\Exceptions\Handler.php Then edit this code:

public function render($request, Exception $exception)
    {
        return parent::render($request, $exception);
    }

to

public function render($request, Exception $exception)
    {
        return response()->json(
            [
                'errors' => [
                    'status' => 401,
                    'message' => 'Unauthenticated',
                ]
            ], 401
        );
    }

Solution 8 - Php

Try this method:

look for this file

> "RedirectifAuthenticated.php"

update the following as you would prefer

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

$guard as an arg will take in the name of the custom guard you have set eg. "admin" then it should be like this.

if (Auth::guard('admin')->check()) {
  return redirect('/admin/dashboard');
}else{
  return redirect('/admin/login');
}

Solution 9 - Php

I ran into this error recently after using Laravel's built-in authentication routing using php artisan make:auth. When you run that command, these new routes are added to your web.php file:

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

I must have accidentally deleted these routes. Running php artisan make:auth again restored the routes and solved the problem. I'm running Laravel 5.5.28.

Solution 10 - Php

Route::post('login', 'LoginController@login')->name('login')

works very well and it is clean and self-explanatory

Solution 11 - Php

Laravel ^5.7

The Authenticate Middleware

Laravel ^5.7 includes new middleware to handle and redirect unauthenticated users.

It works well with "web" guard... of course the "login" route (or whatever you name your login route) should be defined in web.php.

the problem is when your are using custom guard. Different guard would redirect unauthenticated users to different route.

here's a quick workaround based on John's response (it works for me).


app/Http/Middleware/Authenticate.php

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Auth\Middleware\Authenticate as Middleware;

class Authenticate extends Middleware
{
    /**
     * @var array
     */
    protected $guards = [];




    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string[]  ...$guards
     * @return mixed
     *
     * @throws \Illuminate\Auth\AuthenticationException
     */
    public function handle($request, Closure $next, ...$guards)
    {
        $this->guards = $guards;

        return parent::handle($request, $next, ...$guards);
    }




    /**
     * Get the path the user should be redirected to when they are not authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return string
     */
    protected function redirectTo($request)
    {
        if (! $request->expectsJson()) {

            if (in_array('admin', $this->guards)) {
                
                return route('admin.login');
            }

            return route('login');
        }
    }
}

Source : Issue #26292

Solution 12 - Php

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

Name your login route if using your own custom auth system.

Solution 13 - Php

Replace in your views (blade files) all

{{route('/')}} ----- by ----> {{url('/')}}

Solution 14 - Php

If someone getting this from a rest client (ex. Postman) - You need to set the Header to Accept application/json.

To do this on postman, click on the Headers tab, and add a new key 'Accept' and type the value 'application/json'.

Solution 15 - Php

**Adding this for the future me.**
I encountered this because I was reusing Laravel's "HomeController", and adding my custom functions to it. Note that this controller calls the auth middleware in its __construct() method as shown below, which means that all functions must be authenticated. No wonder it tries to take you to login page first. So, if you are not using Laravel's authentication scafffolding, you will be in a mess. Disable the constructor, or do as you seem fit, now that you know what is happening.

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

Solution 16 - Php

//In Laravel 8
Route::post('login', [LoginController::class, 'do'])->name('login');

Solution 17 - Php

If using passport as api do:

routes/web.php:

Route::get('login', function() {
    return response()->json(['message' => 'Unauthorized.'], 401);
});

Route::post('login', [ 'as' => 'login']);

Solution 18 - Php

For Laravel 8 I face the problem while access home url after creating login register system

First there is no route exists with the name login

Just add a route name like this

for single method like

Route::post('put url here',[Your Controller::class,'method name'])->name('login');

for multiple method like

Route::match(['get','post'],'put url here',[Your Controller::class,'method name'])->name('login');

Solution 19 - Php

Route must be valid, should give route name.

Route::group([
    'prefix' => 'v1'
], function () {
    Route::post('/login', [userController::class, 'loginAction'])->name('login');
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioninkdView Question on Stackoverflow
Solution 1 - PhpJeff LambertView Answer on Stackoverflow
Solution 2 - Phpjhon chacollaView Answer on Stackoverflow
Solution 3 - PhpavpView Answer on Stackoverflow
Solution 4 - Phpthangavel .RView Answer on Stackoverflow
Solution 5 - PhpDibyendu Mitra RoyView Answer on Stackoverflow
Solution 6 - PhpNirav ChavdaView Answer on Stackoverflow
Solution 7 - PhpCengkuru MichaelView Answer on Stackoverflow
Solution 8 - PhpCodedreamerView Answer on Stackoverflow
Solution 9 - Phpclone45View Answer on Stackoverflow
Solution 10 - PhpDenise IgnatovaView Answer on Stackoverflow
Solution 11 - PhpchebabyView Answer on Stackoverflow
Solution 12 - PhpsomayView Answer on Stackoverflow
Solution 13 - PhpRubén RuízView Answer on Stackoverflow
Solution 14 - PhpFaiyaz HaiderView Answer on Stackoverflow
Solution 15 - PhpgthuoView Answer on Stackoverflow
Solution 16 - PhpDimitry COULIBALYView Answer on Stackoverflow
Solution 17 - PhpPedramView Answer on Stackoverflow
Solution 18 - PhpNazmul HoqueView Answer on Stackoverflow
Solution 19 - PhpKinjal SuryavanshiView Answer on Stackoverflow