duanganleng0577 2017-10-25 19:39
浏览 387
已采纳

何时使用:redirect('/')vs. redirect() - > route('home')vs。redirect() - > home()?

When I have this named route:
Route::get('/', 'IndexController@index')->name('home');

Then in any action method of any Controller; when I need to redirect to the named route home; any of these statements redirects properly to the intended route:

return redirect('/');
return redirect()->route('home');
return redirect()->home();

When to use each?
What are the differences?
Are there any benefits of using one over the others?

  • 写回答

4条回答 默认 最新

  • donglang5157 2017-10-25 20:40
    关注

    As the documentation mention :

    When you call the redirect helper with no parameters, an instance of Illuminate\Routing\Redirector is returned, allowing you to call any method on the Redirector instance. For example, to generate a RedirectResponse to a named route, you may use the route method

    As you can see in the API methods(link below) there is a lot of methods that you can use and also there is one specific helper method home() it's just a shortcut for redirect()->route('home') as highlighted by @ceejayoz.

    Now the we will talk about return redirect('/'); and return redirect()->route('home'); the two of them redirects properly to the intended route as you said BUT the second one is really useful if in the future.

    Why ?

    Because if you want to change the URL structure in the routes file all you would need to change is the route only for example :

    Route::get('/', 'IndexController@index')->name('home');
    

    Will be :

    Route::get('/home_page', 'IndexController@index')->name('home');
    

    and all the redirects would refer to that route and there is no other thing that you should change => all redirects will still work perfectly.

    BUT

    If you choose to use the first one (i mean return redirect('/');) then after the change in the route you will need to parse all your controllers to check if there is some redirects that uses then changed route and the change them :p

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?