Relational Query In laravel - laravel

My Code
$videos = ExamVideo::with([
'user' => function ($query) use ($request) {
$query->where('user_name', 'like', '%'.$request->search.'%');
}
])->where('is_marked','=', 0)->get();
return $videos;
I want to get only those videos where is_marked is zero & it's relation user_name match my search result.
But I get all the videos which marked is zero.

The with method is only for eager loading and not used to filter your records.
You can accomplish what you want with the whereHas method which will perform a query on the relation:
$videos = ExamVideo::whereHas('user', function ($query) use ($request) {
$query->where('user_name', 'like', "%{$request->search}%");
})->where('is_marked', false)->get();
For more information about whereHas: https://laravel.com/docs/6.x/eloquent-relationships#querying-relationship-existence

Related

Laravel Query Through Relationship

I am creating a search in laravel where customers can search for vehicles.
Table 1
Vehicle
VIN
PLATE
make_and_model_id
Table 2
Vehicle Makes and Models
id
make
model
Relationship in Table 1: Vehicle
public function vehicle_make_and_model_fk()
{
return $this->belongsTo('App\Models\VehicleMakeAndModel', 'vehicle_make_and_model_id');
}
So I am searching for VIN or Plate. That works fine.
I also am Searching for a Make and Model name which is a foreign key.
I pulled in the related table using with which works fine.
Now how to search through the columns of Make and Model Table?
if($request->ajax()) {
$search = $request->search_query;
$vehicles = Vehicle::with('vehicle_make_and_model_fk')
->where(function ($query) use ($search) {
$query->where('plate', 'LIKE', '%'.$search.'%')
->orWhere('vin', 'LIKE', '%'.$search.'%')
->orWhere('vehicle_make_and_models.make', 'LIKE', '%'.$search.'%');
})
->limit(5)
->get();
echo json_encode($vehicles);
exit;
}
To filter the relationship, you need to use a closure in your with()
For example:
$vehicles = Vehicle::query()
->with([
'vehicle_make_and_model_fk' => function ($query) use ($search) {
$query->where('make', 'like', "%$search%")
->orWhere('model', 'like', "%$search%");
}
])
->where(function ($query) use ($search) {
$query->where('plate', 'like', "%$search%")
->orWhere('vin', 'like', "%$search%");
})
->limit(5)
->get();
Eloquent Relationships - Constraining Eager Loads
$vehicles = Vehicle::where('plate','LIKE','%'.$search.'%')
->orWhere('vin','LIKE','%'.$search.'%')
->with('vehicle_make_and_model_fk')
->orwhereHas('vehicle_make_and_model_fk',
function($query) use($search){
$query
->where('vehicle_make_and_models.make','like',$search.'%')
->orWhere('vehicle_make_and_models.model','LIKE','%'.$search.'%');
}
)
->limit(5)
->get();
This query worked. It would search and bring results from vehicle table and would go to makes and models table and bring results from there as well. Based on - Laravel Eloquent search inside related table

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);

search multi column and join another query when a condition is true

i want to search in posts table for a search query, i should search in title and slug columns, also i have a checkbox to search only published posts.
in my code my query always ignore is_publish query. how can i search on only published post when "search on published post" checkbox is checked?
$query = Post::when($request->target, function ($q) use ($request) {
$q->where('title','LIKE', "%$request->target%")->orWhere('slug', 'like', "%$request->target%");
})->when($request->publish, function ($query) use ($request) {
$query->where('is_publish', 1);
});
You can write like as below:
$query = Post::when($request->target, function ($q) use ($request) {
$q->whereRaw("(title LIKE '%$request->target%' or slug LIKE '%$request->target%')")
})->when($request->publish, function ($query) use ($request) {
$query->where('is_publish', 1);
});

Getting a relationship with a condition?

I have category and article tables, they are in a many to many relationship. i have the relationships set up on the models.
How can I get all articles where a category id is = 1?
I've tried:
Article::whereHas('category', function ($query) use ($id) {
$query->where('category_id', $id);
})->get();
The above works, but seems clunky, is there a more efficient way in eloquent to do this?
You can use eager loading technique.
Article::with(['category', function ($query) use ($id) {
$query->where('category_id', $id);
}])->get();
The following groupBy code is assuming that Category::find($id)->articles is not an option for whatever reason.
What about groupBy?
Article::groupBy('category')
->having('category', $id)
->get();
whereHas will return articles that match that condition, but won’t filter articles then fetched by the same conditions. You could therefore create an anonymous function that contains the constraints, and pass it to both the whereHas and with methods:
$filter = function ($query) use ($categoryId) {
$query->where('category_id', '=', $categoryId);
};
Article::whereHas('category', $filter)
->with(['category' => $filter])
->get();

Looping inside an eagerly loaded closure in Laravel

I am using function of Laravel eloquent model.
Here is the code:-
$keywords = ['name1', 'name2', 'name3'];
$authors = App\Author::with(['books' => function ($query) use ($keywords) {
// $query->where('name', 'like', '%name2%');
foreach ($keywords as $name) {
$query->orWhere('name', 'like', "%$name%");
}
}])->get();
I am trying to return all authors along with books where the name of the book matches the values in a given array of keywords. I have used foreach loop to go through multiple orwhere() like conditions, but the condition does not seem to be working. However, the commented out statement is working fine for me.

Resources