2015-04-21 33 views
3

我不確定我是否正確使用它,但我正在利用Laravel 5中的請求來檢查用戶是否已登錄,以及他是否是一個東西。爲此,我需要獲取請求類中的實際對象,但是我需要在控制器中獲取相同的對象?Laravel 5請求:授權,然後解析對象到控制器

因此,我沒有將它提取兩次,而是想,爲什麼不把對象設置爲請求類中的變量,使其可以被控制器訪問?

它的作品,但我覺得很髒?有沒有更適當的方法來處理這個問題?

Ex。 請求類

class DeleteCommentRequest extends Request { 

    var $comment = null; 

    public function authorize() { 
     $this->comment = comment::find(Input::get('comment_id')); 
     $user = Auth::user(); 

     if($this->comment->user == $user) 
      return true; 

     return false; 
    } 

    public function rules() { 
     return [ 
      'comment_id' => 'required|exists:recipes_comments,id' 
     ]; 
    } 
} 

例。 控制器:

public function postDeleteComment(DeleteCommentRequest $request) { 
     $comment = $request->comment; 
     $comment->delete(); 
     return $comment; 
} 

那麼,什麼是我的問題嗎?如何在使用新的Laravel 5請求時最好地處理使用對象兩次?我是否可能過度使用應用程序的功能?將對象存儲在應用程序類中是否可以,以便稍後可以在控制器中訪問它?

+1

好了,我不知道最乾淨的方式,但你可以讓它通過例如短很多'返回Comment :: find(Request :: input('comment_id')) - > user_id == Auth :: id();'不是說這是一個好方法,而是把它扔到那裏。 –

回答

1

我會要求查詢本身的所有權,然後檢查收集是否爲空。

class DeleteCommentRequest extends Request { 

     var $comment = null; 

     public function authorize() { 
      $this->comment = comment::where('id',Input::get('comment_id'))->where('user_id',Auth::id())->first(); 

      if($this->comment->is_empty()) 
       return false; 

      return true; 
     } 

     public function rules() { 
      return [ 
       'comment_id' => 'required|exists:recipes_comments,id' 
      ]; 
     } 
    } 
1

既然你想使用的模式在兩個不同的地方,但只能查詢一次我會重新開始使用route-model binding

在你的RouteServiceProvider類(或任何相關的提供者)中,你需要綁定來自boot方法內部的註釋查詢。 bind()的第一個參數將是匹配路由中通配符的值。

public function boot() 
{ 
    app()->router->bind('comment_id', function ($comment_id) { 
     return comment::where('id',$comment_id)->where('user_id',Auth::id())->first(); 
    }); 
} 

一旦這樣設置,你可以從你的DeleteCommentRequest訪問模式,像這樣

$this->comment_id 

注:該變量COMMENT_ID因爲那是你的路線一致,但將包含實際的模型。

從你的控制器,你只是注入它像這樣

public function postDeleteComment(Comment $comment, DeleteCommentRequest $request) { 
     $comment->delete(); 
     return $comment; 
}