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

coder72's avatar

How to get All Consumer Data ?

This is my Sales Table.

id | sales | consumer_id | user_id
 1 | 23    |      1      |    2
 2 | 43    |      2      |  2
 3 | 38    |      2      |  2
 4 | 198    |      1      |  3

This is my Consumers Table

id | name | 
 1 | arju    |
 2 | kara    |
 3 | pemb    |
 4 | dran    |

This is my Sales model look like

 public function consumer()
    {
        return $this->belongsTo('App\Consumer', 'consumer_id');
    }

Suppose My User Id is 2.I want to get all consumer where my user_id is 2 in sales table.If my user_id is 1 the i need all consumer from sale table where user_id 1.So how should do it

0 likes
5 replies
Sergiu17's avatar
Sale::with('customer')->where('user_id', 2)->get();
coder72's avatar

I tried like this.It worked.

$sales=Sale::with('customer')->where('user_id', 2)->groupBy('consumer_id')->get();
  $consumers=[];
foreach($sales as $sale){
	   array_push($consumers,$sale->consumer);
}
coder72's avatar

Yes I tried this.but i donot know whtether this method is good or not

$sales=Sale::with('customer')->where('user_id', 2)->groupBy('consumer_id')->get();
  $consumers=[];
foreach($sales as $sale){
	   array_push($consumers,$sale->consumer);
}
MichalOravec's avatar
Level 75
$customers = Customer::whereHas('sales', function ($query) {
    $query->where('user_id', 2);
})->get();

Please or to participate in this conversation.