Laravel - Query "with"

Northify picture Northify · Oct 17, 2014 · Viewed 24.9k times · Source

I have a query where I need to get info from 2 tables. So I need to get invoices with the invoice_status 1, where the user_status is 1. I though I could query the Invoices table with the users table. when I dd($invoices) I do get the invoice with the users just fine...

$invoices = Invoice::with('user')->where('invoice_status', '=', 2)->get();

But I'm not sure sure how I can get the users->account_status. I tried this but get a query error it can not find account_status.

$invoices = Invoice::with('user')->where('invoice_status', '=', 2)->where('account_status', '=', 1)->get();

Answer

rdiz picture rdiz · Oct 17, 2014

You can pass in a closure to handle the query for the eager-loaded content:

$invoices = Invoice::with(array('user' => function($query) {
    $query->where('account_status', '=', 1);
}))->where('invoice_status', '=', 2)->get();