如何在Laravel中进行即时重定向 [英] How to make instant redirection in Laravel

查看:43
本文介绍了如何在Laravel中进行即时重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Laravel中的控制器中进行即时重定向.

I want to make an instant redirection in my controller in Laravel.

我知道我可以使用

public function show($page) 
{   
   return Redirect::url('http://example.com');
}

但是我想在许多添加条件的控制器中重复此代码,例如,我想做这样的事情:

but I want to repeat this code in many controllers adding condition for example I would like to do something like this:

public function show($page) 
{
  $totalPages = 100; // here calculating maximum page

  if ($page < 2 || $page > $totalPages)  {
     return Redirect::url('http://example.com');
  }    
  // rest of code here - should be run if condition is false
}

但是我不想在每个控制器中重复代码.

but I don't want to repeat code in each controller.

如果我尝试将重定向代码放入其他方法(可能存在于基本控制器中),将无法正常工作,因为它在主控制器中未返回任何内容:

If I try put redirection code in other method (that could exist in base controller) it won't work because it doesn't return anything in main controller:

public function show($page) 
{
  $totalPages = 100; // here calculating maximum page
  $this->checkPages($page, $totalPages, 'http://example.com');   

 // rest of code here - should be run if condition is false   
}

public function checkPages($page, $totalPages, $url) 
{
  if ($page < 2 || $page > $totalPages)  {
     return Redirect::url($url);
  }    
}

我该如何解决这个问题?

How can I solve this issue?

推荐答案

经过一段时间的挖掘,看来您应该使用Symfony\Component\HttpFoundation中的send()方法(Laravel RedirectResponse继承自此类).

After a while of digging it seems that for this purposes you should use send() method from Symfony\Component\HttpFoundation (Laravel RedirectResponse inherits from this class).

因此您可以通过以下方式修改checkPages方法:

So you can modify checkPages method this way:

public function checkPages($page, $totalPages, $url) 
{
  if ($page < 2 or $page > $totalPages)  {
     Redirect::url($url)->send();
  }    
}

它将立即进行重定向.

这篇关于如何在Laravel中进行即时重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆