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?
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'));
}
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'));
}
Route::post('login', 'LoginController@login')->name('login')
works very well and it is clean and self-explanatory
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.
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'.
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');
}));
**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');
}
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
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');
}
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
);
}
Source: Stackoverflow.com