I have 2 tables in my Laravel application namely customers and stores. Customers can belong to many stores and stores can have many customers. There's a pivot table between them to store that relation.
Question is, how do I extract the list of customers for a given store using Eloquent? Is it possible? I am currently able to extract that using Laravel's Query Builder. Here is my code:
| customers | stores | customer_store |
-------------------------------------------
| id | id | customer_id |
| name | name | store_id |
| created_at| created_at | created_at |
| updated_at| updated_at | updated_at |
Customer Model:
public function stores(){
return $this->belongsToMany(Store::class)
->withPivot('customer_store', 'store_id')
->withTimestamps();
}
Store Model:
public function customers(){
return $this->belongsToMany(Customer::class)
->withPivot('customer_store', 'customer_id')
->withTimestamps();
}
DB Query (using Query Builder):
$customer = DB::select(SELECT customers.id, customers.name, customers.phone, customers.email, customers.location FROM customers LEFT JOIN customer_store on customers.id = customer_store.customer_id WHERE customer_store.store_id = $storeID);
Try this one:
public function result(Request $request) {
$storeId = $request->get('storeId');
$customers = Customer::whereHas('stores', function($query) use($storeId) {
$query->where('stores.id', $storeId);
})->get();
}
Try executing this...
$result = Customer::with('stores')->get();
Hope this helps.
To know more about Eloquent Relationship refer: https://laravel.com/docs/5.1/eloquent-relationships
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With