Laravel 5重定向到带参数的路径(不是路由名称)

时间:2016-01-04 07:32:07

标签: php redirect laravel-5.1 laravel-routing

我一直在阅读,但无法在重定向中找到重定向和包含参数的方法。

此方法仅适用于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');

修改

基于documentation,第二个参数用于http状态代码,这就是我收到上述错误的原因。我认为它的工作方式就像URL外观URL::to('schools/edit', [$school->id])正常工作。

问题2

解决此问题的最佳方法是什么(不使用路由别名)?我应该重定向到Controller操作吗?就个人而言,我不喜欢这种方法对我来说似乎太长了。

我也不喜欢使用别名,因为我已经在整个应用程序中使用了路径,而且我担心如果添加别名,它可能会影响现有路径?否?

2 个答案:

答案 0 :(得分:0)

您是否观看了课程Illuminate\Routing\Redirector

您可以使用:

public function route($route, $parameters = [], $status = 302, $headers = [])

这取决于您创建的路线。如果您在app\Http\Routes.php中创建如下:

获取('学校/编辑/ {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']);

This is pretty basic.

PS。如果您的学校控制器是基于资源(CRUD),您可以创建resource(),它将创建基本路线:

Route::resource('schools', 'SchoolController');
// or
$router->resource('schools', 'SchoolController');

PS。别忘了在工匠那里看你创造的路线

答案 1 :(得分:0)

redirect("schools/edit/$id");

或(如果您愿意)

redirect("schools/edit/{$id}");

只需构建所需的路径。

'命名'路由不会改变任何URI。它允许您通过其名称在内部引用路由,而不必在任何地方使用路径。

相关问题