我有这个blogsController,创建函数如下.
public function create() {
if($this->reqLogin()) return $this->reqLogin();
return View::make('blogs.create');
}
Run Code Online (Sandbox Code Playgroud)
在BaseController中,我有这个功能,它检查用户是否登录.
public function reqLogin(){
if(!Auth::check()){
Session::flash('message', 'You need to login');
return Redirect::to("login");
}
}
Run Code Online (Sandbox Code Playgroud)
这段代码工作正常,但它不是我需要的创建函数,如下所示.
public function create() {
$this->reqLogin();
return View::make('blogs.create');
}
Run Code Online (Sandbox Code Playgroud)
我可以这样做吗?
除此之外,我可以设置身份验证规则,就像我们在Yii框架中一样,在控制器的顶部.
tac*_*one 12
除了组织代码以适应更好的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;
}
}
Run Code Online (Sandbox Code Playgroud)
在PHP中的用法:
redirect_now('/');
Run Code Online (Sandbox Code Playgroud)
刀片中的用法:
{{ redirect_now('/') }}
Run Code Online (Sandbox Code Playgroud)
您应该将检查放入过滤器中,然后仅让用户在首先登录的情况下访问控制器。
筛选
Route::filter('auth', function($route, $request, $response)
{
if(!Auth::check()) {
Session::flash('message', 'You need to login');
return Redirect::to("login");
}
});
Run Code Online (Sandbox Code Playgroud)
路线
Route::get('blogs/create', array('before' => 'auth', 'uses' => 'BlogsController@create'));
Run Code Online (Sandbox Code Playgroud)
控制器
public function create() {
return View::make('blogs.create');
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7573 次 |
| 最近记录: |