Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch All users who has at least one post in laravel

Please guide me,

How can I get all users in Laravel, who has posted at least single post. And skip who has not posted any posts.

I am trying this. But it is getting All users.

$users = User::with('post')->get(); 
like image 313
Harry Avatar asked May 09 '17 12:05

Harry


3 Answers

Try has() method for Eloquent models -> https://laravel.com/docs/5.4/eloquent-relationships

$users = User::with('post')->has('post')->get();

You can take users with active posts using whereHas(). Remember it. :)

$users = User::with('post')->whereHas('post', function ($query) {
    $query->where('is_active', '=', true);
})->get();
like image 93
Patryk Woziński Avatar answered Nov 20 '22 12:11

Patryk Woziński


You can use :

User::with('post')->has('post')->get();

or whereHas (from laravel doc)

// Retrieve all posts with at least one comment containing words like foo%
$posts = Post::whereHas('comments', function ($query) {
    $query->where('content', 'like', 'foo%');
})->get();
like image 21
Bara' ayyash Avatar answered Nov 20 '22 12:11

Bara' ayyash


Try this:

$users = User::has('post')->get(); 
like image 1
Khalid Dabjan Avatar answered Nov 20 '22 13:11

Khalid Dabjan