mistre83's avatar

Dependency Injection with relation

Hi to All!

I've just started to study Laravel, and I have a simple application (post -> comments) and when i load the post X, I want to load comments too (in descending order, for example).

If i write a router like this, i have "for free" the query on Post (by id) but i cant set the order (or pagination, for example):

Route::get('/post/{id}', 'PostController@getPost');

And, the controller:

public function getPost(Post $post) {...}

In a situation like this, where i have to do "more than a simple query", will be better to create the controller without DI, and write the query inside this ? (or in the model, or elsewhere..)

public function getPost($id) {...}
0 likes
4 replies
TheNodi's avatar

@mistre83

You have the post you're asking for, now you need to query the comments and order them. I don't think you need to order the post query since only one results will be returned.

Let's say you have set up a one-to-many relationship between posts and comments, you can return all post's comments with:

public function getPost(Post $post) {
    $comments = $post->comments;
}

But since you may want to order them, you can get the "raw" query and apply the extra rules:

public function getPost(Post $post) {
    $comments = $post->comments()->orderBy('date', 'desc')->get();
}

And the pagination can be applied to it as well because $post->comments() returns a query builder instance. (To be precise, it returns a relation that you can treat as a query, see Relation::_call)

1 like
mistre83's avatar

Yes, in Post model i have the oneToMany relation.

Right now, the Controller is simple and i just return the post to the View:

public function index(Post $post = null)
{
    return view('post.index', compact('post'));
}

With this, in the View i can use @foreach ($post->comments as $comment) and the loop through them.

What i need to do, is to pass another variable ($comments) and in the View use this instead of $post->comments ?

TheNodi's avatar

@mistre83

I personally prefer to pass an additional $comments variable so you can have all your order/filter logic in the controller.

mistre83's avatar

Great! Also because right now i have something like this (the oneToMany relation):

public function comments()
{
    return $this->hasMany(Comment::class)->orderBy('created_at', 'desc');
}

And this is very very bad. So, i will modify my controller passing another variable and then i use it in the View (and no more $post->comments)

Please or to participate in this conversation.