【问题标题】:Laravel 5.6 - Get Route By Name In ControllerLaravel 5.6 - 在控制器中按名称获取路由
【发布时间】:2018-12-24 23:00:22
【问题描述】:
在我的登录控制器中,有一个硬编码的 URL 字符串,用于设置用户登录后重定向到的位置。我试图通过按名称获取路由来使其动态化:
protected $redirectTo = '/home';
更新到:
protected $redirectTo = route('home');
但是上面给出了以下错误:
致命错误异常 (E_UNKNOWN)
常量表达式包含无效操作
是否可以通过名称获取路由的 URL?
【问题讨论】:
标签:
laravel
authentication
routes
【解决方案1】:
你可以使用
request()->route()->getName()
获取您将使用的网址
request()->url()
还有路径
request()->path()
当前路线方法
request->route()->getActionMethod()
对于redirectTo,您可以覆盖该函数:
protected function redirectTo() {
return route('foo.bar');
}
【解决方案2】:
你必须定义一个名为home的路由
像这样:
Route::get('/home', 'HomeController@index')->name('home');
或Route::get('/home', ['as' => 'home', 'uses' => 'HomeController@index']);
【解决方案3】:
获取路由url的另一种方式
$route_url = \Request::route()->getURLByName("name of the route");
【解决方案4】:
您的问题是在类中声明属性时不允许使用函数调用。您应该使用控制器的构造函数来设置它:
class LoginController extends Controller
{
protected $redirectTo = '/home';
public function __construct()
{
$this->middleware('guest')->except('logout');
$this->redirectTo = route('home');
}
}
或者,您可以定义一个redirectTo 方法,该方法返回您希望用户在成功登录后重定向到的位置。然后,您可以完全删除 $redirectTo 属性:
class LoginController extends Controller
{
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function redirectTo()
{
return route('home');
}
}
【解决方案5】:
protected $redirectTo = route('home');
您不能将函数分配给属性。这就是您收到此错误的原因。
你可以在你的构造函数中这样做
public function __construct(){
$this->redirectTo = route('home')
}
【解决方案6】:
这是我使用的方式,它将与您一起使用。只需将此功能放入您的 LoginController 以覆盖已验证的功能。
protected function authenticated(Request $request, $user)
{
return redirect()->route('your_route_name');
}