我到处都在读,但找不到重定向和在重定向中包含参数的方法。
这个方法只适用于flash消息,所以我不能使用它。
return redirect('user/login')->with('message', 'Login Failed');
此方法仅适用于具有别名的路由。我的routes.php
当前未使用别名。
return redirect()->route('profile', [1]);
问题1
有没有一种方法可以在不定义路由别名的情况下使用路径?
return redirect('schools/edit', compact($id));
当我使用这种方法时,我会得到这个错误
InvalidArgumentException with message 'The HTTP status code "0" is not valid.'
我的路线下有这个:
Route::get('schools/edit/{id}', 'SchoolController@edit');
编辑
根据文档,第二个参数用于http状态代码,这就是我收到上面错误的原因。我认为它像URL
立面一样工作,其中URL::to('schools/edit', [$school->id])
工作得很好。
问题2
解决此问题的最佳方法是什么(不使用路由别名)?我应该改为重定向到控制器操作吗?就我个人而言,我不喜欢这种方法对我来说太长了
我也不喜欢使用别名,因为我已经在整个应用程序中使用了路径,我担心如果我添加别名,可能会影响现有路径?不
redirect("schools/edit/$id");
或者(如果你喜欢的话)
redirect("schools/edit/{$id}");
只需构建所需的路径。
"命名"路由不会更改任何URI。它将允许您通过路由名称在内部引用路由,而不必在任何地方使用路径。
你看Illuminate'Routing'Redirector
课了吗?
您可以使用:
public function route($route, $parameters = [], $status = 302, $headers = [])
这取决于您创建的路线。如果你在app'Http'Routes.php
中这样创建:
get('schools/edit/{id}','SchoolController@edit');
然后您可以通过以下方式创建路线:
redirect()->action('SchoolController@edit', compact('id'));
如果你想使用route()
方法,你需要命名你的路线:
get('schools/edit/{id}', ['as' => 'schools.edit', 'uses' => 'SchoolController@edit']);
// based on CRUD it would be:
get('schools/{id}/edit', ['as' => 'schools.edit', 'uses' => 'SchoolController@edit']);
这是非常基本的。
PS。如果你的学校控制器是基于资源(CRUD)的,你可以创建一个resource()
,它将创建基本路线:
Route::resource('schools', 'SchoolController');
// or
$router->resource('schools', 'SchoolController');
PS。别忘了仔细观察您创建的路线