Brandy
Brandy

Reputation: 564

Laravel 5.4 Eloquent where parent

So I have two models setup, User and Post. Post has a belongsTo setup of user and User has a hasMany setup for posts.

When getting all my posts, I want to make sure the user isn't banned. Banned is an int in the database in a column called ban and I want to make sure it's equal to 0. I originally looped through the posts, checked to make sure user wasn't banned and then pushed it to an array and passed that array to the view which was working fine. However, I now want to enable paginate and it's broken because I'm not passing in the eloquent object.

Here is my eloquent right now:

$posts = Post::where('status', '>', 1)->orderBy('published_date', 'desc')->paginate(10);

Upvotes: 1

Views: 3912

Answers (1)

Ehs4n
Ehs4n

Reputation: 802

Use whereHas()

$posts = Post::where('status', '>', 1)->whereHas('user', function($q) {
    $q->where('ban', 0);
})->orderBy('published_date', 'desc')->paginate(10);

I assume, you have user relation on User model from Post model.

Upvotes: 8

Related Questions