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

RodrigoG's avatar

1-n query by id with eloquent

Hello everyone, I would like to know if there is a better way to do this type of query, I have achieved it through a sub query but I want to know if there is a better or more efficient way with eloquent, the case is that in a one-to-many relationship what I want the query to return is, passing a specific element through id, it returns all the elements related to it. That is, between a job and a client I want him to return all the works of a single client. Thanks!!

My code:

public function render()
{
    $works = Work::where('client_id',$this->client->id)
    ->where(function ($query) {
        $query->where('id','like','%' . $this->search . '%')
        ->orWhere('code_work','like','%' . $this->search . '%')
        ->orWhere('date','like','%' . $this->search . '%')
        ->orWhere('description','like','%' . $this->search . '%');
    })->orderBy($this->sort, $this->direction)->paginate(10);

    return view('livewire.admin.clients.works',['works' => $works]);   
}

I tried this but not work:

public function render()
{
    $works = Work::with('client')->find($this->client->id)->where('id','like','%' . $this->search . '%')
        ->orWhere('code_work','like','%' . $this->search . '%')
        ->orWhere('date','like','%' . $this->search . '%')
        ->orWhere('description','like','%' . $this->search . '%')
        ->orderBy($this->sort, $this->direction)->paginate(10);

    return view('livewire.admin.clients.works',['works' => $works]);   
}
0 likes
2 replies
Snapey's avatar

it's not a subquery

In your first example you are just wrapping brackets around some of the terms so that the orwhere does not interfere with the client id

where in the id field seems out of place here

you can still add with('client') in the first example

1 like
RodrigoG's avatar

Ok, thank you for the reply. Is it true, I can add with ('client') and make it more efficient, then the first is the best way to do this kind of query?

Please or to participate in this conversation.