or where clause - Laravel eloquent - laravel

I have this query:
if($keyword){
array_push($where, ['name_en', 'LIKE', '%'.$keyword.'%']);
}
The problem is that I have and name_fr column and I need to use OR clause - array_push($where, ['name_fr', 'LIKE', '%'.$keyword.'%']).
I can't use ->orWhere, because I have many dynamic search fields - they may exists or not.
For the example:
if($fromPrice){
array_push($where, ['price', '>=', $fromPrice]);
}
if($toPrice){
array_push($where, ['price', '<=', $toPrice]);
}
And the query is:
$cars= Property::with(array(
'photos'=>function($query){
$query->select(['car_id', 'name']);
}
))->where($where)->paginate(10);
I need to select WHERE name_en LIKE %val% OR name_fr LIKE %val% with another queries.
Is there a way to use somehow where, 'OR' and LIKE in the above way including another values from $where array ?

to achieve that a suggest you to divide your query as below and don't put your keyword condition within $where array:
$query = Property::with(array(
'photos'=>function($query){
$query->select(['car_id', 'name']);
}
))->where($where);
if($keyword){
$query = $query->where(function ($query) use ($keyword) {
$query->where('name_fr', 'like', $keyword)
->orWhere('name_en', 'like', $keyword);
});
}
$cars = $query->paginate(10);

You can also go with
$propertyQuery = Property::query();
if($keyword){
$propertyQuery->where(function($query) use ($keyword){
$query->where('name_fr', 'LIKE', '%'.$keyword.'%')->orWhere('name_en', 'LIKE', '%'.$keyword.'%');
});
}
$cars = $propertyQuery->paginate(10);

Related

Laravel how to Order by relation in scope?

I have the following scope in User model
$query->with('country')
->when($filters['search'] ?? null, function ($query, $search) {
return $query->where('name', 'LIKE', '%' . $search . '%')
->orWhereHas('country', function ($query) use ($search) {
$query->where('name', 'LIKE', '%' . $search . '%');
});
});
$query->orderBy('name', 'asc');
}
return $query;
}
I am pretty new to Laravel - I currently the above query is sorting by user name but I would like to sort by country name. I can do this with country_id as there is a relation but not sure how to sort by country name.
Thanks
there are two approaches we can use to order these users by their company. The first is using a join:
$users = User::select('users.*')
->join('countries', 'countries.id', '=', 'users.country_id')
->orderBy('companies.name')
->get();
Here is the generated SQL for this query:
select users.*
from users
inner join countries on countries.id = users.country_id
order by countries.name asc
The second way is using a subquery:
$users = User::orderBy(Country::select('name')
->whereColumn('countries.id', 'users.country_id')
)->get();
And you can see the reference here: ordering database queries by relationship columns in laravel

Laravel - whereHas query not returning correct records

I am currently writing a search query but I'm having issues joining a where with a whereHas
if I wanna search for categories only..
The below query works if I just search for categories solo
$goals = $myGoals
->whereHas('categories', function ($q) use ($search) {
$q->where('name', 'like', "%$search%");
})->paginate(10);
if I wanna search for the title only..
Same as above if I wanna search for the title of goals solo
$goals = $myGoals->where('title', 'like', "%$search%" )->paginate(10);
both of the queries work if I want to search for them individually.
Query attempt
Below is the query I've written to allow a user to search for the title of a goal and the name of a category.
$myGoals = $team->goals();
$goals = $myGoals
->whereHas('categories', function ($q) use ($search) {
$q->where('name', 'like', "%$search%");
})->where('title', 'like', "%$search%" )->paginate(10);
I have tried the above query but the search results return empty when I enter an input. I've also tried swapping the where() to orWhere() which then returns a goal that doesn't belong to the $team model instance but it's a goal record linking to a different Team model id within the pivot table.
Can anyone spot where I am going wrong? thanks
You need to use it all inside where.
$goals = $myGoals->where(function ($query) use ($search){
return $query->whereHas('categories', function ($q) use ($search) {
$q->where('name', 'like', "%$search%");
})->orWhere('title', 'like', "%$search%" );
})->paginate(10);

Laravel with where like condition in relationship

I have a WorkPackage model with below relationship.
public function work_items()
{
return $this->hasMany(WorkItem::class);
}
And WorkPackage has 'title','project_id' columns and work_items has 'title','work_package_id' columns. Now I want to search user typed keyword is matching with title in both table.
Here is my tried function
public function getWorkPackageProposals($projectId, $title)
{
$result['data'] = $this->workPackage->with(['work_items' => function ($query) {
$query->where('title', 'LIKE', "%{$title}%");
}])
->where('project_id', $projectId)
->where('title', 'LIKE', "%{$title}%")
->get();
return $result;
}
but its not working.
Please find the below code for I used to create object of WorkPackage.
public function __construct(WorkPackage $workPackage)
{
$this->workPackage = $workPackage;
$this->setModel(WorkPackage::class);
$this->workItemRepository = app(WorkItemRepository::class);
}
whereHas() works to specify additional filters for the related model to check :
$result['data'] = $this->workPackage->whereHas('work_items', function ($query) use ($title) {
$query->where('title', 'LIKE', "%{$title}%");
})
->where('project_id', $projectId)
->where('title', 'LIKE', "%{$title}%")
->get();
return $result;
Below code works for me. Thanks to everyone for help to get right answer.
$result['data'] = $this->workPackage->with(['work_items' => function ($q) use ($title) {
$q->where('title', 'LIKE', "%{$title}%");
}])
->where('project_id', $projectId)
->where('title', 'LIKE', "%{$title}%")
->get();
return $result;
I think your problem will be solved with join method:
$result = $this->workPackage
->join('work_items', 'work_packages.id', '=', 'work_items.package_id')
->where('work_items.title', 'LIKE', '%{$term}%')
->orWhere('work_packages.title', 'LIKE', '%{$term}%')
->get();

Laravel break up paginated eloquent query

I currently have:
$comments = $this->post->comments()
->where('comment', 'like', "%{$search}%")
->paginate(50);
But I'd like to do something like the below, as I have multiple filters that I'm going to apply:
$comments = $this->post->comments();
if(condition)
{
$comments->where('comment', 'like', "%{$search}%");
}
$comments->paginate();
But the code above doesn't work as I then get errors on things like $comments->links() for pagination links in the view, indicating that this doesn't work.
What you can try is something like this, I don't know what Laravel version you are using, also I don't know the structure you have of your models, but here's the documentation about this example:
$conditions = 1;
$comments = Post::with('comments')
->whereHas('comments', function ($query) use ($conditions){
// pass your conditions
if(!$conditions){
$query->where('comment', 'like', "%%")
}
// more conditions, etc
$query->where('comment_id', 'like', '%%');
})->paginate(50);
It was missing $comment = in front of the query clauses:
$comments = $this->post->comments();
if(condition)
{
$comments = $comments->where('comment', 'like', "%{$search}%");
}
$comments = $comments->paginate();

Is there a way for Eloquent whereHas to only get() the matching results?

I have the following function
public function index(Request $request)
{
$results = Service::whereHas('conditions', function ($query) use ($request){
$query->whereIn('id', $request->conditions);
})
->whereHas('locations', function ($query) use ($request){
$ran = false;
foreach($request->locations as $location)
{
if(!$ran)
{
$query->Where('town', 'like', '%'.$location.'%')
->orWhere('city', 'like', '%'.$location.'%');
}
else
{
$query->orWhere('town', 'like', '%'.$location.'%')
->orWhere('city', 'like', '%'.$location.'%');
}
$ran = true;
}
})
->with('types', 'contacts', 'locations.datetimes')->toSql();
dd($results);
}
which produces
select * from `services` where exists
(select * from `conditions` inner join `condition_service` on `conditions`.`id` = `condition_service`.`condition_id` where `services`.`id` = `condition_service`.`service_id` and `id` in (13, 14) and `conditions`.`deleted_at` is null)
and exists
(select * from `service_locations` inner join `service_location_service` on `service_locations`.`id` = `service_location_service`.`service_location_id` where `services`.`id` = `service_location_service`.`service_id` and
(`town` like 'manchester' or `city` like 'manchester' or `town` like 'crewe' or `city` like 'crewe')
and `service_locations`.`deleted_at` is null) and `services`.`deleted_at` is null
The problem is the whereHas on locations brings back all results, whereas I only want the result where the town/city is a match. Whats the best way to achieve this?
i think you need to group your location query using the callback which wraps the query in () and just process the first location directly remove it from array and iterate over loop. so below code should work in your case.
$results = Service::whereHas('conditions', function ($query) use ($request){
$query->whereIn('id', $request->conditions);
})
->whereHas('locations', function ($query) use ($request){
$locations = $request->locations;
$query->where(function($builder) use($locations){
$builder->where('town', 'like', '%' . $locations[0] . '%')
->orWhere('city', 'like', '%'.$locations[0].'%');
unset($locations[0]); //remove first item as it is processed
foreach($locations as $location) {
$builder->orWhere('town', 'like', '%'.$location.'%')
->orWhere('city', 'like', '%'.$location.'%');
}
});
});
let me know if you find any problem with it. :)
I managed to figure it out late last night.
I moved the with() to the top of the query and made a callback on locations.
public static function newGetSearchResults($request)
{
return Service::with(['types', 'contacts', 'locations.datetimes', 'locations' => function($query) use($request) {
$ran = false;
foreach($request->locations as $location)
{
if(!$ran)
{
$query->Where('town', 'like', '%'.$location.'%')
->orWhere('city', 'like', '%'.$location.'%');
}
else
{
$query->orWhere('town', 'like', '%'.$location.'%')
->orWhere('city', 'like', '%'.$location.'%');
}
$ran = true;
}
}])
->whereHas('conditions', function ($query) use ($request){
$query->whereIn('id', $request->conditions);
})->get();
}

Resources