Laravel Relationships - Select rows with same column value in blade

987 views Asked by At

Let's say I have a post with many comments and I properly defined $post->comments relation in my post model. Comments have a column named confirmed with the value of 0 or 1. How can I select confirmed (rows which have confirmed value of 1) rows in my blade template?

2

There are 2 answers

3
Goms On BEST ANSWER

This can help you In your Post model

public function comments()
{
    return $this->hasMany(Comment:class);
}

public function confirmedComments()
{
    return $this->comments()->whereConfirmed(1);
}

And from your controller

$comments = $post->confirmedComments;

If in blade, you want select confirmed comments, it's so easy to do it with

@if($comment->confirmed)
    //confirmed comment
@else
   //
@endif

Hope it'll be helpful !

1
patricus On

There are many ways to do this.

If you already have the comments eager loaded, then you can use the where() method on the comments collection:

$confirmedComments = $post->comments->where('confirmed', 1);

This will go through all the comments in the collection and only return those that are confirmed.

If you don't have the existing collection, you can add the where clause to the relationship query. This way, you're only getting confirmed comments from the database, and you're not wasting resources retrieving and building models for comments you're not using

$confirmedComments = $post->comments()->where('confirmed', 1)->get();

And, another option, would be to create a new relationship for just confirmed comments, and that way you can eager load the new relationship:

public function comments()
{
    return $this->hasMany(Comments::class);
}

public function confirmedComments()
{
    return $this->comments()->where('confirmed', 1);
}

$confirmedComments = $post->confirmedComments;