John Davidson

php - whereHas is not working properly. I want to search by location name, which is not working

0 comments
Message:


I have two table customers, locations, and pivot table customer_location. I want to display Customer with id 3 with location, and then I can search that by location's name, customer's name, domain, number, or by email.


public function getCustomersProperty()
{
$search = $this->search;

return Customer::with('locations')->where('id', '=', '3')
->whereHas('locations', function ($q) use ($search) {
$q->where('name', 'like', '%'.$search.'%');
})
->where(function ($q) {
$q->Where('name', 'like', '%'.$this->search.'%')
->orWhere('domain', 'like', '%'.$this->search.'%')
->orWhere('number', 'like', '%'.$this->search.'%')
->orWhere('email', 'like', '%'.$this->search.'%');
})
->orderBy($this->sortField, $this->sortDirection)
->paginate($this->page_number);
}


My Answer:
In your code, the issue might be with the whereHas clause for searching by location name. Make sure that the relationship between Customer and Location is correctly defined in your models.

Here is an updated version of your code that should work for searching by location name:

php
public function getCustomersProperty()
{
$search = $this->search;

return Customer::with('locations')
->where('id', '=', '3')
->whereHas('locations', function ($q) use ($search) {
$q->where('name', 'like', '%'.$search.'%');
})
->where(function ($q) use ($search) {
$q->where('name', 'like', '%'.$search.'%')
->orWhere('domain', 'like', '%'.$search.'%')
->orWhere('number', 'like', '%'.$search.'%')
->orWhere('email', 'like', '%'.$search.'%');
})
->orderBy($this->sortField, $this->sortDirection)
->paginate($this->page_number);
}


Make sure that the relationship between Customer and Location is correctly defined in your models. Also, ensure that the 'name' column exists in the locations table and that the pivot table customer_location is set up correctly.

If you continue to experience issues, you may need to check your database structure and relationships to ensure everything is set up correctly for the search functionality to work as expected.

Rate this post

5 of 5 based on 2797 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us