Skip to content
Advertisement

Laravel 5.2 – Selecting only articles that has comments

I built a commenting system, and I’m working on a page that shows all the comments that are waiting for approval.

The relationship:

Article.php

public function comments()
{
    return $this->hasMany('AppArticleComment');
}

ArticleComment.php

public function article()
{
    return $this->belongsTo('AppArticle');
}

Now, I want to select only the articles that have comments that are waiting for approval (status column on article_comments table equals 0).

Any easy way of doing it? (Of course I can get all articles and check on each one if it has comments)

Advertisement

Answer

The other answer will work but you asked for an easy (also re-usable) approach to use so I would suggest to create a scope method in your ArticleComment model using something like the following:

In your Article model:

use AppArticleComment;
use IlluminateDatabaseEloquentModel;

class Article extends Model {

    // Relation for comments
    public function comments()
    {
        return $this->hasMany(ArticleComment::class);
    }

    // Relation for pending comments
    public function pendingComments()
    {
        return $this->comments()->pending();
    }
}

In your ArticleComment model:

// Query scope for pending comments
public function scopePending($query)
{
    $query->whereStatus(0);
}

So, you can use something like this:

$posts = Post::has('pendingComments')->get();

Also, you may chain with like:

$posts = Post::has('pendingComments')->with('pendingComments')->get();
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement