在laravel中重定向而不返回语句


Redirection in laravel without return statement

我有这个blogsController,创建函数如下。

public function create() {
  if($this->reqLogin()) return $this->reqLogin();
  return View::make('blogs.create');
 }

在BaseController中,我有这个功能,可以检查用户是否登录

    public function reqLogin(){
      if(!Auth::check()){
        Session::flash('message', 'You need to login');
        return Redirect::to("login");
      }
    }

这段代码运行得很好,但这不是我想要的创建函数所需要的。

public function create() {
  $this->reqLogin();
  return View::make('blogs.create');
 }

我可以这么做吗?

除此之外,我可以像在Yii框架中那样,在控制器的顶部设置身份验证规则吗。

除了组织代码以更好地适应Laravel的架构外,当无法返回响应并且绝对需要重定向时,还可以使用一个小技巧。

诀窍是调用'App::abort()并传递相应的代码和标头。这将适用于大多数情况(尤其不包括刀片视图和__toString()方法)

这里有一个简单的函数,无论发生什么,它都可以在任何地方工作,同时保持关闭逻辑的完整性。

/**
 * Redirect the user no matter what. No need to use a return
 * statement. Also avoids the trap put in place by the Blade Compiler.
 *
 * @param string $url
 * @param int $code http code for the redirect (should be 302 or 301)
 */
function redirect_now($url, $code = 302)
{
    try {
        'App::abort($code, '', ['Location' => $url]);
    } catch ('Exception $exception) {
        // the blade compiler catches exceptions and rethrows them
        // as ErrorExceptions :(
        //
        // also the __toString() magic method cannot throw exceptions
        // in that case also we need to manually call the exception
        // handler
        $previousErrorHandler = set_exception_handler(function () {
        });
        restore_error_handler();
        call_user_func($previousErrorHandler, $exception);
        die;
    }
}

PHP中的用法:

redirect_now('/');

刀片中的用途:

{{ redirect_now('/') }}

我们可以这样做,

throw new 'Illuminate'Http'Exceptions'HttpResponseException(redirect('/to/another/route/')->with('status', 'An error occurred.'));

您应该将检查放入过滤器中,然后只有在用户首先登录的情况下才允许用户访问控制器。

过滤器

Route::filter('auth', function($route, $request, $response)
{
    if(!Auth::check()) {
       Session::flash('message', 'You need to login');
       return Redirect::to("login");
    }
});

路线

Route::get('blogs/create', array('before' => 'auth', 'uses' => 'BlogsController@create'));

控制器

public function create() {
  return View::make('blogs.create');
 }

使用这种方法不是最佳实践,但为了解决您的问题,您可以使用此要点。

创建一个助手函数,如:

if(!function_exists('abortTo')) {
  function abortTo($to = '/') {
    throw new 'Illuminate'Http'Exceptions'HttpResponseException(redirect($to));
  }
}

然后在你的代码中使用它:

public function reqLogin(){
  if(!Auth::check()){
    abortTo(route('login'));
  }
}
public function create() {
  $this->reqLogin();
  return View::make('blogs.create');
}