未定义路由[登录]

今天第一次和 Laravel 一起玩。当我尝试访问 localhost/project/public 时,出现以下错误:

InvalidArgumentException
未定义路由[登录]。

App/routes.php:

<?php


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

应用程序/控制器/HomeController.php:

<?php


class HomeController extends Controller {


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


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


}

App/controller/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/controller/DashboardController.php:

<?php


class DashboardController extends Controller {


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


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


}

为什么我会得到这个错误?

252953 次浏览

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.

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

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

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

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.

Replace in your views (blade files) all

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

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

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'

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

works very well and it is clean and self-explanatory

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

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

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'.

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

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


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

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

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

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

Route must be valid, should give route name.

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

If using passport as api do:

routes/web.php:

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


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