Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

eddy1992's avatar

Laravel relationship eloquent query

Hi Guys, I am using Laravel5.6* and I have a relationship between the products and users.

App\Product Model 
/**
	 * each product belongs to a user
	 * @return [type] [description]
	 */
	public function user()
	{
		return $this->belongsTo('App\User', 'users_user_id', 'user_phone');
	}

Now I want to get all the products which have a category id 3 and I also want to get the number of ads the users have.

$categoryId = 3;
        $from =  '2021-11-08';
        $to = '2022-01-08';
        $ads = Product::with('user')
        ->select('product_id', 'users_user_id')
        ->where('categories_category_id', $categoryId)
        ->whereBetween('newdate', [$from, $to])
        ->get();

This above query would give me the user ids saved in the ads which are of category id 3 but how could I get the number of ads the users have in the same query?

Is that possible? Please assist.

0 likes
4 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

Something like this? (assumes an ads relationship on user)

$categoryId = 3;
        $from =  '2021-11-08';
        $to = '2022-01-08';
        $ads = Product::with(['user' => function ($query) {
    $query->withCount('ads');
} ])
        ->select('product_id', 'users_user_id')
        ->where('categories_category_id', $categoryId)
        ->whereBetween('newdate', [$from, $to])
        ->get(); 
eddy1992's avatar

Thank you for your reply @Sinnbeck

I have this relationship for the users in the products model

 App\User model

	public function products()
	{
		return $this->hasMany('App\Product', 'users_user_id', 'user_phone');
	}

Keeping this relationship in mind will your query work with this?

Please or to participate in this conversation.