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

mailnike's avatar

Where clause in eloquent join

Hi,

Is there anyway to add where clause in the eloquent join? I have relationship setup between invoice table, contact (customer) table and status table. Column 'name' & 'text' mentioned in the below code are part of the table "contact" & "InvoiceStatus".

Here is my API code. It works perfectly when I don't pass FILTER in my API URL. However, it fails when I pass HTTPS://URL/api/invoices?filter=abcd . Laravel throws an error "column 'name' not found. as it doesn't exist in the invoice table but exists in the contact table:

    if (request()->has('sort')) {
        list($sortCol, $sortDir) = explode('|', request()->sort);
        $query = Invoice::orderBy($sortCol, $sortDir)
            ->with('InvoiceStatus','contact') //invoice belongs to status & contact
            ->where('id','=',$id); //need to replace company with team
    } else {
        $query = Invoice::orderBy('id', 'asc')
            ->with('InvoiceStatus','contact')
            ->where('id','=',$id);
    }


    if ($request->exists('filter')) {
        $query->where(function($q) use($request) {
            $value = "%{$request->filter}%";
            $q->where('name', 'like', $value)   //name is a part of the conact table
                ->orWhere('text', 'like', $value); //text is a part of the InvoiceStatus 
        });
    }
0 likes
3 replies
mailnike's avatar

@w1n78 what if we are not using JOIN? I am using relationship. How do I add where clause?

Please or to participate in this conversation.