Laravel query using whereIn not working when insert array of data - laravel

I try to get data for promotion using whereIn, but the query give error.
In whereIn, if I make whereIn('category_id', [123,2323]) no error.
But when I try to get data from request($data2 = $request->category;), I cannot use with whereIn
$promotions = Promotion::with('product')->with('category')->whereHas(
'category',
function ($q) {
$data2 = $request->category;
$q->whereIn('category_id', $data2);
})
->paginate(9);

You need to use use($request)
$promotions = Promotion::with('product')->with('category')->whereHas(
'category',
function ($q) use ($request){
$data2 = $request->category;
$q->whereIn('category_id', $data2);
})
->paginate(9);
Sample data for $request->category. I return data as json and display using javascript console.log()

Related

Laravel, eloquent, query: problem with retriving right data from DB

I'm trying to get the right data from the database, I'm retriving a model with a media relation via eloquent, but I want to return a photo that contains the 'main' tag stored in JSON, if this tag is missing, then I would like to return the first photo assigned to this model.
how i assign tags to media
I had 3 ideas:
Use orWhere() method, but i want more likely 'xor' than 'or'
$models = Model::with(['media' => function ($query) {
$query->whereJsonContains('custom_properties->tags', 'main')->orWhere();
}]);
return $models->paginate(self::PER_PAGE);
Raw SQL, but i don't really know how to do this i tried something with JSON_EXTRACT and IF/ELSE statement, but it was to hard for me and it was a disaster
Last idea was to make 2 queries and just add media from second query if there is no tag 'main'
$models = Model::with(['media' => function ($query) {
$query->whereJsonContains('custom_properties->tags', 'main');
}]);
$models_all_media = Model:: with(['media']);
return $models->paginate(self::PER_PAGE);
but i tried something like
for($i=0; $i<count($models); $i++) {
$models->media = $models_all_media
}
but i can't do this without get() method, beacuse i don't know how to change this to LengthAwarePaginator class after using get()
try using whereHas https://laravel.com/docs/9.x/eloquent-relationships
Model::with('media')
->whereHas('media',fn($media)=>$media->whereJsonContains('custom_properties->tags', 'main'))
->paginate(self::PER_PAGE);
as per your comment you can use
$models = Model::with(['media' => function ($query) {
$query->whereJsonContains('custom_properties->tags', 'main');
}])
->leftJoin('media', function ($join) {
$join->on('models.id', '=', 'media.model_id')
->whereNull('media.custom_properties->tags->main');
})
->groupBy('models.id')
->paginate(self::PER_PAGE);
return $models;

OrderByRaw in Laravel

I am making an app that filters products
I want to add this query chunk to my $products = $products-> newQuery();
I'm using $products = $products-> newQuery(); Because I am querying with filters. Example:
$products = $products->newQuery();
if ($request->has('brand') && !empty($brand)) {
$products->where('brand', '=', $brand);
}
if ($request->has('size') && !empty($size)) {
$products->whereHas('stocks', function($query) use ($size) {
$query->where('size', '=', $size);
});
}
I want to add this query
$best_sellers = OrderItem::select('product_id')->groupBy('product_id')->orderByRaw('SUM(quantity) DESC')->limit(2)->get();
I have previously used it in another method and it works but I don't know how to integrate it
I tried:
$products->whereHas('order_items', function($query) {
$query->select('product_id')->groupBy('product_id')->orderByRaw('SUM(quantity) DESC');
});
But it hasn't worked
Any idea? thanks
Updated with Error:
you need to use with() to add relationship data whereHas() it just for filter it does not add new key
example
$products->with(['order_items'=> function ($q) {
$q->select('product_id')->groupBy('product_id')->orderByRaw('SUM(quantity) DESC')->limit(2)->get();
}]);

DB::raw convert to query builder

Can you help me to convert the Raw part of my query to use query builder?
I am stuck at joining it all together:
$profile = UserProfiles::select('id')->where('alias', $profileAlias)->first();
$dbRawMessagesCount = '
(SELECT COUNT(pm.id)
FROM profile_messages pm
WHERE pm.to_profile_id='.$profile->id.'
AND pm.from_profile_id=profile_friend.id
AND pm.is_read=0) AS messages_count
';
$friends = ProfileFriend::select('profile_friend.*', DB::raw($dbRawMessagesCount))
->with('friendProfile')
->whereHas('ownerProfile', function ($query) use ($profile) {
return $query->where('id', $profile->id);
})
->orderBy('messages_count')
->paginate();
You can rewrite this into one query if ProfileFriend has a relation already set up to ProfileMessages using withCount() in the query.
$friends = ProfileFriend::with('friendProfile')
->withCount(['profileMessages' => function($q) use($profile){
$q->where('to_profile_id', $profile->id)->where('is_read', 0);
// No longer need 'from_profile_id' as it is already querying the relationship
}])
->whereHas('ownerProfile', function ($query) use ($profile) {
return $query->where('id', $profile->id);
})
->paginate();
Now if you dd($friends->first()) you will notice it has a field called profileMessages_count that gives you a count of what I'm assuming is unread messages.

Laravel remove parent if related collection

I have a model with a related collection
now im doing this query
$data = DeliveryPartner::when($filter, function ($q) use ($request) {
})
->with(['orders' => function ($query) {
$query
->where('delivery_partner_invoice_id', '=', '')
->orWhereNull('delivery_partner_invoice_id')
->whereIn('status', ['payment-accepted', 'completed', 'full-refund', 'partial-refund']);
}])->get();
Now i am wondering. If the orders returns empty is it posible to remove this parent from the collection?
I Know i can do this after the eloquent query with a loop. But is it possible to do this in the query?
we cant completely remove that parent ( with index ) BUT you can set those to null using transform() like this;
$data = DeliveryPartner::when($filter, function ($q) use ($request) {
})
->with(['orders' => function ($query) {
$query
->where('delivery_partner_invoice_id', '=', '')
->orWhereNull('delivery_partner_invoice_id')
->whereIn('status', ['payment-accepted', 'completed', 'full-refund', 'partial-refund']);
}])->get()->transform(function($item){
if(!$item->orders->count() ){
return;
}
return $item;
});
Note: this will not completely remove those parents but it will set them to empty.

Laravel eloquent using loop

I am using eloquent query to filter data. My query is like this and it is working perfectly for now.
$users = User::where('username','LIKE','%'.request('username').'%')
->where('first_name','LIKE','%'.request('first_name').'%')
->where('last_name','LIKE','%'.request('last_name').'%')
->where('gender','LIKE','%'.request('gender').'%')
->where('password','LIKE','%'.request('password').'%')
->SimplePaginate(15);
My request data was like this.
However I need to update this query for dynamic fields. There can be different fields. What I did was to send the request in an associative array. So, my request data turned into like this,
What I intend to do is to put all request data in a search array. Then use a loop to run like the above query. How can I do that?
P.S. I checked in the forum and found some similar questions. Some of them are outdated. Others didn't solve my problem.
If I understand you right you can do like this:
$search = request('search', []);
$users = User::query();
foreach($search as $field=>$value)
{
$users = $users->where($field,'LIKE','%'.$value.'%');
}
$users = $users->SimplePaginate(15);
You can try this.
$search = $request->get('search');
User::where(function ($q) use ($search){
foreach ($search as $key=>$value) {
if($value != null ){
$q->where($key, 'like', "%{$value}%");
}
}
})->get();
The where() clause can also accept an array. With that in mind, you could map over your search parameters and convert it to the format you want and then feed it into the query.
For example:
$search = [
'first_name' => 'John',
'last_name' => 'Smith'
];
$filters = collect($search)->map(function($value, $key) {
return [$key, 'LIKE', "%{$value}%"];
})->values()->toArray();
return User::where($filters)->SimplePaginate(15);

Resources