whereHas query in Laravel - php

Hello guys,
$filterArray = explode("_", $filters);
$data['articles'] = \DB::table('products')->join('product_category', function ($q) {
$q->on('product_category.product_id', '=', 'products.id');
})->where('product_category.category_id', '=', $id)
->select('products.*')
->whereBetween('price_retail_1', array($priceFrom, $priceTo))
->whereHas('filters', function ($query, $filterArray) {
$query->whereIn('filter_id', $filterArray);
})
->orderBy('products.' . $sort, $sortOrder)
->get();
}
I have the following query and I'm having some issues on the whereHas method. I'm getting an error
Unknown column 'has' in 'where clause
most likely because the $filterArray variable is out of scope for the function ( or at least that is what I am guessing. Any help on how to solve the issue is appreciated.

You cannot use whereHas method in the Query Builder context. The whereHas method is only for Eloquent Query Builder that is comming from the Eloquent models and their relationships.
What you can do is to use joins. So you can try like this:
$filterArray = explode("_", $filters);
$data['articles'] = \DB::table('products')->join('product_category', function ($q) {
$q->on('product_category.product_id', '=', 'products.id');
})->where('product_category.category_id', '=', $id)
->select('products.*')
->whereBetween('price_retail_1', array($priceFrom, $priceTo))
->join('filters', 'products.filter_id', '=', 'filters.filter_id')
->whereIn('filter_id', $filterArray);
->orderBy('products.' . $sort, $sortOrder)
->get();
I don't know how you connecting these two tables so here is only the example data:
->join('filters', 'products.filter_id', '=', 'filters.filter_id')

Related

Can not use where clause after using with clause in Laravel query

I am writing a query using with and then where clause in laravel.
$users = User::query()->with('roles')->where('name', '!=', 'customer')->get();
return $users;
But where clause is not working here. Customers are not excluded. I am providing the snap shot of the query result.
I think you need whereHas() :
use Illuminate\Database\Eloquent\Builder;
$users = User::query()
->with('roles')
->whereHas('roles', function (Builder $query) {
$query->where('name', '!=', 'customer');
})
->get();
return $users;
I suppose you trying to filter relation data in base query.
Try smth like that:
$users = User::query()->with([
'roles' => function ($q) {
$q->where('name', '!=', 'customer');
}])
->get();
return $users;
Doc

Laravel Eloquent hardcoded value in whereNotIn

In Laravel eloquent query using multiple columns for whereNotIn clause I need to hardcoded one of the DB::raw column for the value should be coming from a variable (loop variable). What is the best way to implement this?
This is my query and I need to change the hardcoded 1 in DB::raw('(1,user_profile.user_id')
$otherProfiles = Userprofile::where('user_id', '!=', $profile->user_id)
->where(function ($query) use ($userInterests) {
foreach ($userInterests as $interest) {
$query->orWhere('interest', 'like', "%$interest%");
};
})
->whereNotIn(DB::raw('(1, user_profile.user_id)'), function ($query) {
$query->select('sender_id', 'receiver_id')
->from('email_reports');
})
->inRandomOrder()
->get();
Manage to fix it by just simple concatenation
the code added were DB::raw('('. $profile->user_id . ', user_profile.user_id)')
create a variable as $id for your dynamic value..
$otherProfiles = Userprofile::where('user_id', '!=', $profile->user_id)
->where(function ($query) use ($userInterests) {
foreach ($userInterests as $interest) {
$query->orWhere('interest', 'like', "%$interest%");
};
})
->whereNotIn('user_id', $id), function ($query) {
$query->select('sender_id', 'receiver_id')
->from('email_reports');
})
->inRandomOrder()
->get();

Laravel Collection Query, Where I am going wrong?

My tables looks like this
area_trip
|id|dispatch_id|trip_id|status|
equipment_trip
|equipment_id|trips_id|dispatch_id|
trips
|id|dispatch_id|status
I am trying to pass collection to my resource. Can someone check my query and tell me what I am doing wrong as following query returning all the data matches dispatch_id whether it matches equipment_id or not. Btw I am new to laravel.
return
Resources::collection(
area_trip::where('dispatch_id', $request->dispatch_id)
->where('status', 1)
->orWhere('status', 9)
->whereHas('equipment_trip', function($query) use ($request) {
$query->where('equipment_trip.equipment_id', '=', $request->equipment_id);
})
->with(['equipment_trip', 'createdBy', 'updatedBy', 'area', 'trips'])
->orderBy('tripStartDate', 'ASC')
->orderBy('status', 'ASC')
->get());
Here is the relationship set up in area_trip model
public function equipment_trip()
{
return $this->belongsTo(equipment_trip::class, 'trip_id', 'trips_id');
}
I believe your whereHas sub query is incorrect also instead of where and orWhere use where in and you can define all statuses necessary, try this:
Resource::collection(area_trip::where('dispatch_id', $request>dispatch_id)
->whereIn('status', [1, 9])
->whereHas('equipment_trip', function($query) use ($request) {
return $query->where('equipment_id', '=', $request->equipment_id);
})
->with(['equipment_trip', 'createdBy', 'updatedBy', 'area', 'trips'])
->orderBy('tripStartDate', 'ASC')
->orderBy('status', 'ASC')
->get());

Call to a member function whereHas() on a non-object in laravel

In my controller I have wrote this following code
$usersCount = User::where('activated', '=', 1)->where('group_id', '=', 1)->where('availability_date', '<=', $opportunity_date)->count();
$locations_array_result = explode(",",$locations_array_result);
foreach ($locations_array_result as $param)
{
$usersCount = $usersCount->whereHas('location', function($q) use($param){
$q->where('location_id', '=', $param );
});
}
This code giving following error
Call to a member function whereHas() on a non-object
Can anyone help me to find out what i have done wrong!!!
$usersCount is already a number from the 1st line of your sample.
You want instead to replace $usersCount->whereHas with User::whereHas in your foreach loop.
Taking a very wild guess here, I would think you need to get all users with these requirements
->where('group_id', '=', 1)->where('availability_date', '<=', $opportunity_date)
plus having a location_id value which exists on an array named $locations_array_result
If this is the case, this is all you need:
User::where('activated', '=', 1)->where('group_id', '=', 1)->where('availability_date', '<=', $opportunity_date)->whereIn('location_id', $locations_array_result)->get();
EDIT
Following your comment below, I assume user has many to many relation with locations (defined in your model), so eager loading and then using a condition with a callback should do the job:
$users = User::where('activated', '=', 1)
->where('group_id', '=', 1)
->where('availability_date', '<=', $opportunity_date)
->with(array('location' => function($query) use ($locations_array_result)
{
$query->whereIn('location_id', $locations_array_result);
}))->get();

Laravel eloquent SQL query with OR and AND with where clause

I know that sql AND can be achieved by consecutive where clauses. and OR with where(condition,'OR').
I want to choose all the messages from message table where sentTo = editor_id AND sentFrom= currentUser_id OR where sentTo = currentUser_id AND sentFrom = editor_id.
I have this query which I am trying to get the result through,
$this->data['messages'] = Message::where(function ($query) use($uId) {
$query->where('sentTo', '=', $this->data['currentUser']->id)
->orWhere('sentFrom', '=', $uId);
})
->where(function ($query) use($uId){
$query->where('sentTo', '=', $uId)
->orWhere('sentFrom', '=', $this->data['currentUser']->id);
})
->get();
How can I do this? Please advice.
I'm a bit confuse as you didn't provide parentheses to know which operator precedence you want.
Assuming you want WHERE (editor_id=$editorId AND sentFrom=$currentUserId) OR (sentTo=$currentUserId AND sentFrom=$editorId) then latest version of Laravel allows you to do:
Message::where(['editor_id' => $editorId, 'sentFrom' => $currentUserId])
->orWhere(['sentTo' => $currentUserId, 'sentFrom' => $editorId])->get();
No need to use closures.
Try this
$this->data['messages'] = Message::where(function ($query) use($uId) {
$query->where('sentTo', '=', $this->data['currentUser']->id)
->where('sentFrom', '=', $uId);
})-> orWhere(function ($query) use($uId){
$query->where('sentTo', '=', $uId)
->Where('sentFrom', '=', $this->data['currentUser']->id);
})->get();

Categories