Conditionals on multiple Laravel relationships - laravel

I got table called Vehicles in whose model Vehicle are defined two relationships.
public function type(){
return $this->belongsTo("App\VehiclePivot", 'vehicle_type_id', "id");
}
and
public function workOrganization(){
return $this->belongsTo("App\WorkOrganization", 'workOrganization_id', "id");
}
When used as
$vehicles = Vehicle::with("type", "workOrganization");
they work great. Show for every vehicle their type and their work organization.
If i try
$vehicles = Vehicle::whereHas("type", function($query) use($request){
$query->where('name', '=', $request->type);
})->with("type")->get();
or
$vehicles = Vehicle::whereHas("workOrganization", function($query) use($request){
$query->where('name', '=', $request->workOrg);
})->with("workOrganization")->get();
They also work.
User can enter type or workOrganization, or both or neither of them.
If one is present, then only that relationship should "execute", if both, then both relationship should, also if it neither of them, then also both should execute.
Can it be done via eloquent?

I think you can use when
$vehicles = Vehicle::when(!empty($request->workOrg),function ($query) use($request){
$query->whereHas("workOrganization", function($query) use($request){
$query->where('name', '=', $request->workOrg);
});
})->when(!empty($request->type),function ($query) use($request){
$query->whereHas("type", function($query) use($request){
$query->where('name', '=', $request->type);
});
})
->with("workOrganization","type")
->get();

Related

Laravel model get all results, but if model has relation then check for certain condition

Assume I have book models and borrow models. They are one-to-many relationships. I want to get a collection of all the books but return the result if the book is borrowed within the current week. But if it's not, then don't display. I've been trying whereHas(), but I think it didn't suit what I'm looking for.
$displayed_books = Books::orderBy('updated_at', 'DESC')
->ifHasborrow('borrow', function ($query) {
$query->where('start_date', '>=', currentweek())
->where('end_date', "<=", currentweek());
})
$displayedBooks = Books::orderBy('updated_at', 'DESC')
->where(function ($query) {
$query->whereHas('borrow', function($query) {
$now = Carbon::now();
$query->where([
['start_date', '>=', $now->startOfWeek()],
['end_date', '<=', $now->endOfWeek()]
]);
$query->orWhereDoesntHave('borrow');
})
})->get();

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 Eloquent making select on whereHas()

How can I select on whereHas() some columns in relation.
My current query looks like as it follows
Location::select(['title'])
->withCount(['job' => function($q) {
return $q->where('language_id', 1)->whereNull('deleted_at');
}])->whereHas('country', function ($q) {
return $q->where('id', '=', 80);
})->get();
and I tried
Location::select(['title', 'id as value'])->withCount(['job' => function($q) {
return $q->where('language_id', 1)->whereNull('deleted_at');
}])->whereHas('country', function ($q) {
return $q->select('title', 'iso3')->where('id', '=', 80);
})->get();
but nothing is getting returned on country relation. How do I refactor this query to get it work?
whereHas() doesn't eager load the relation, only filters results based on it. To eager load, use with().
Location::with('country:id,title,iso3')
->select(['title', 'id as value', 'country_id'])
->withCount(['job' => function($q) {
$q->where('language_id', 1)->whereNull('deleted_at');
}])
->whereHas('country', function ($q) {
$q->where('id', '=', 80);
})->get();

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 5.8: orWhere anulls the whereHas effect

I'm trying to do a simple search function. For that, I implemented the following query:
Profile::whereHas('accounts', function ($query) use ($id) {
$query->where('user_id', $id);
})
->where('username', 'LIKE', "%{$search}%")
->paginate(20);
The whereHas selects the profiles that the user with $id has.
Then, with the where we figure out if the search match with some username in the database.
Finally, we paginate the results.
All right so far.
The problem comes when I add a orWhere like that:
Profile::whereHas('accounts', function ($query) use ($id) {
$query->where('user_id', $id);
})
->where('username', 'LIKE', "%{$search}%")
->orWhere('fullname', 'LIKE', "%{$search}%")
->paginate(20);
I want that the query analyses if the search matchs with the username and/or the fullname. When I add the orWhere works, but the whereHas doesn't do its work and the results are from all the users.
You need to do it like this:
Profile::whereHas('accounts', function ($query) use ($id) {
$query->where('user_id', $id);
})
->where(function($query) use ($search) {
$query->where('username', 'LIKE', "%{$search}%")
->orWhere('fullname', 'LIKE', "%{$search}%");
})
->paginate(20);

Resources