Laravel 5 requests: authorize and then parse object to controller
I'm not sure if I am using this correctly, but I am using queries in Laravel 5 to check if a user is logged in and if they own an object. For this I need to get the actual object in the request class, but then I need to get the same object in the controller?
So instead of fetching it twice, I thought, why not just set the object as a variable in the request class, making it available to the controller?
It works, but am I feeling dirty? Is there a better way to handle this?
Ex. Request class
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'
];
}
}
Ex. Controller:
public function postDeleteComment(DeleteCommentRequest $request) {
$comment = $request->comment;
$comment->delete();
return $comment;
}
So what's my question? What's the best way to handle using an object twice when using new Laravel 5 requests? Perhaps I am overloading the functionality of the application? Is it possible to store the object in the application class so that I can retrieve it later in my controller?
source to share
I would need to own the query itself and then check if the collection is empty.
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'
];
}
}
source to share
As you want to use the model in two different places, but only ask for it as soon as I resumed using binding to the route model .
In your RouteServiceProvider class (or any relevant provider), you will want to bind the comment request inside the load method. The first parameter to bind () will be a value that matches the pattern in your route.
public function boot()
{
app()->router->bind( 'comment_id', function ($comment_id) {
return comment::where('id',$comment_id)->where('user_id',Auth::id())->first();
} );
}
After this setup, you can access the model from your DeleteCommentRequest, for example
$this->comment_id
Note. This variable is the Comment_id as it matches your route, but it will contain the actual model.
From your controller, you simply inject it like this:
public function postDeleteComment(Comment $comment, DeleteCommentRequest $request) {
$comment->delete();
return $comment;
}
source to share