Laravel 5.6 - Get Route By Name In Controller
Solution 1
You can use
request()->route()->getName()
To get the url you would use
request()->url()
And the path
request()->path()
Current route method
request->route()->getActionMethod()
In the case of redirectTo
you can override the function:
protected function redirectTo() {
return route('foo.bar');
}
Solution 2
Your problem is that you're not allowed to use a function call when declaring a property in your class. You should use your controller's constructor to set it:
class LoginController extends Controller
{
protected $redirectTo = '/home';
public function __construct()
{
$this->middleware('guest')->except('logout');
$this->redirectTo = route('home');
}
}
Alternatively, you can define a redirectTo
method which returns the location that you want the user to be redirected to after a successful login. You can then remove the $redirectTo
property altogether:
class LoginController extends Controller
{
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function redirectTo()
{
return route('home');
}
}
heady12
Updated on June 05, 2022Comments
-
heady12 almost 2 years
Within my login controller there is a hardcoded URL string which sets where to redirect to once the user has logged in. I am trying to make this dynamic by getting the route by name:
protected $redirectTo = '/home';
Updated To:
protected $redirectTo = route('home');
However the above give the following error:
FatalErrorException (E_UNKNOWN) Constant expression contains invalid operations
Is it possible to get the URL to the route by its name?
-
Bas almost 6 yearslook in the middleware directory, there is an auth file, thats the place
-