Ad

Laravel 6 Route Issue When Try To Redirect

- 1 answer

I am trying to redirect to login page when anyone hit home page in URL, but always it give error like

Route [admin/login] not defined.

Many questions is there with same issue but does not solve the issue.

Also the same route work if directly type in URL then it work, but redirect from the Authenticate.php is not working.

routes/web.php

Route::get('/', function () {
    return view('welcome');
});

Auth::routes();
// Admin Routes

// Without auth
Route::group(['prefix' => 'admin', 'namespace' => 'Auth'], function () {
  Route::get('/login', '[email protected]');

});



Route::group(['prefix' => 'admin', 'namespace' => 'Auth', 'middleware' => 'auth:admin'], function () {

  Route::get('/home', '[email protected]');

});

Authenticate.php

namespace App\Http\Middleware;

use Illuminate\Auth\Middleware\Authenticate as Middleware;

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

            if ($request->is('admin') || $request->is('admin/*')) {
                return route('admin/login');
            } else if ($request->is('vendor') || $request->is('vendor/*')) {
                return route('vendor/login');
            } else {
                return route('login');
            }


        }
    }
}
Ad

Answer

You don't name your routes, so you can't call them like this, you need to use :

Route::group(['prefix' => 'admin', 'namespace' => 'Auth'], function () {
   // just add the name to the route to call route('login')
   Route::get('/login', '[email protected]')->name('login');
});

Then you can call :

return route('login');

Or if you don't want to name your routes, use instead :

return redirect('admin/login');

EDIT :

My mistake, you use redirectTo function, so you just need to return a string, use this :

return 'admin/login';
Ad
source: stackoverflow.com
Ad