search in table related to eloquent
I have 3 related tables and I need to search for data but using eloquent and not query builder. it's possible?
public function render()
{
$data_products = Product::with('brand', 'category')->orderBy('id', 'desc')
->where('name', 'like', '%' . $this->search . '%')
->paginate($this->perPage);
return view('livewire.products', compact('data_products'));
}
example I would like to search by brand name or category.
Thanks.
@datanorte You can use whereHas() in that case. I assume that brand table has name field and category has title filed those you want to search.
public function render()
{
$data_products = Product::with('brand', 'category')->orderBy('id', 'desc')
->where('name', 'like', '%' . $this->search . '%')
->orWhereHas('brand', function($query) use($search = $this->search){
$query->where('name', '%' . $search . '%')
})->orWhereHas('category', function($query) use($search = $this->search){
$query->where('title', '%' . $search . '%')
})->paginate($this->perPage);
return view('livewire.products', compact('data_products'));
}
Note: You need to adjust the query based on your requirements.
Ref: https://laravel.com/docs/8.x/eloquent-relationships#querying-relationship-existence
I am if it works, is it good practice?
public function render()
{
$filter = $this->search;
$data_products = Product::whereHas('brand', function ($query) use ($filter) {
$query->where('name', 'like', '%' . $filter . '%');
})->orWhereHas('category', function ($query) use ($filter) {
$query->where('name', 'like', '%' . $filter . '%');
})
->orWhere('name', 'like', '%' . $filter . '%')
->orderBy('id', 'desc')
->paginate($this->perPage);
return view('livewire.products', compact('data_products'));
}
Please or to participate in this conversation.