2014-08-30 53 views
6

我有这个blogsController,创建函数如下。重定向在laravel没有return语句

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'); 
} 

我可以吗?

除此之外,我可以设置authantication规则,就像我们在Yii框架中那样,在控制器的顶部。

+0

Yii不等于laravel。为什么标签Yii。 – crafter 2014-08-31 13:11:26

+0

我想要一个已经在两者上工作过的人的回答。 – anwerj 2014-09-01 05:21:03

回答

2

您应该将支票放入筛选器中,然后只让用户在首次登录时进入控制器。

过滤

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' => '[email protected]')); 

控制器

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

This works!,so I need to add route for every action我需要授权吗? – anwerj 2014-08-30 10:47:31

+0

查看Laravel文档中的Route :: group()。基本上把一组“授权路线”组合在一起。 – Laurence 2014-08-30 11:58:55

8

除了组织代码,以更好地适应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('/') }} 
+0

谢谢@alexxali – tacone 2015-01-16 21:49:59

+0

'\ App :: abort($ code);'很棒! +1谢谢! :) – emotality 2017-08-24 18:59:24