Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5: How to do a join query on a pivot table using Eloquent?

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);
like image 506
captainblack Avatar asked Dec 20 '16 05:12

captainblack


Video Answer


2 Answers

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();

}
like image 152
Alex Lam Avatar answered Sep 28 '22 19:09

Alex Lam


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

like image 27
kapil.dev Avatar answered Sep 28 '22 18:09

kapil.dev