Search code examples
laravelrelationships

Laravel Relationships - Select rows with same column value in blade


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?


Solution

  • 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 !