Laravel:如何在控制器方法执行后重定向

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43061040/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:40:27  来源:igfitidea点击:

Laravel: How to redirect after controller method execution

phplaravelredirectblade

提问by Sahand

web.php:

web.php

Route::post('caption/{id}/delete', 'DetailController@deleteCaption');

DetailController.php:

DetailController.php

public function deleteCaption(Request $request, $id) {
    $caption = Caption::findOrFail($id);
    $caption->delete(); //doesn't delete permanently

    return response(204);
}

admin.blade.php:

admin.blade.php

<p value='{{$caption->id}}'>{{$caption->content}}</p>
<form action="caption/{{$caption->id}}/delete" method="post">
<button type="submit">Delete caption</button>
</form> 
<form action="caption/{{$caption->id}}/approve" method="post">
<button type="submit">Accept caption</button>
</form>     

I want to make it so that after I delete an image, the user is redirected back to the admin page, located at localhost:8000/admin.

我想这样做,以便在我删除图像后,用户被重定向回位于 localhost:8000/admin 的管理页面。

How can I do this? Documentation isn't understandable to me.

我怎样才能做到这一点?文档对我来说是无法理解的。

回答by Zugor

You can redirect like

你可以像重定向一样

public function deleteCaption(Request $request, $id) {
    $caption = Caption::findOrFail($id);
    $caption->delete(); //doesn't delete permanently

    return redirect()->to('link/to/anywhere');
}

OR
You can redirect like this

或者
你可以像这样重定向

return redirect()->back();

to your last state.

到你最后的状态。

OR

或者

return route('yourRouteName');
//if there's parameters
return route('yourRouteName', ['id' => 1]);

回答by jeremykenedy

You can simply redirect to your defined route in your web.php:

您可以简单地重定向到您在 web.php 中定义的路由:

public function deleteCaption(Request $request, $id) {
    $caption = Caption::findOrFail($id);
    $caption->delete(); //doesn't delete permanently

    return redirect('admin');
}

https://laravel.com/docs/5.4/responses#redirects

https://laravel.com/docs/5.4/responses#redirects

Checking out the routing and blade docs may assist as well.

检查路由和刀片文档也可能有所帮助。

https://laravel.com/docs/5.4/routing

https://laravel.com/docs/5.4/routing

https://laravel.com/docs/5.4/blade

https://laravel.com/docs/5.4/blade

回答by Y M

Since you want to return back to the same page. You can use Laravel's back function.

由于您想返回到同一页面。你可以使用 Laravel 的 back 函数。

 return back();

To redirect user back to the page it came from.

将用户重定向回它来自的页面。

回答by Nirbhay Kularia

To redirect back use

重定向回使用

return redirect()->back();

To redirect to specific route use

重定向到特定路由使用

return return redirect()->route('route-name');