2014-08-30 54 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