Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

seewhy's avatar

Writing eloquent Query

I have two queries I will like to re-write. The first one is a raw query I would like to re-write using eloquent

DB::select('select * from asks WHERE amount IN (select MIN(amount) as lowest_ask from `asks` where `product_uuid` = ? group by `shoe_size_id`)', [$this->uuid]);

This gets the lowest ask for each shoe size if you need some context.

I tried many iterations but it all failed, here is the last one I did tried

Ask::where('amount', function($query) use ($product_id) {
  $query->select([
  	DB::raw('MIN(amount) as lowest_ask'),
	])
    ->where('product_uuid', $product_id)
    ->groupBy('shoe_size_id')
    ->get();
});

but it did not work

The second is a regular whereHasquery on a polymorphic many to many relationship.

$products->whereHas('brand', function ($query) use ($request) {
    $query->where('name', $request->get('brand'));
});				

I will love to re-write this using a join. I have made several attempts but could not. Thanks for the help

0 likes
5 replies
LoaiDev's avatar

If you want to get the one Ask that has the lowest price for a product you can do this

Ask::where('product_uuid', $product_id)
	->orderBy('amount', 'asc')
	->first();

If you have the product model itself (and have "asks" relationship) you can do something similar like this

$product->asks()
	->orderBy('amount', 'asc')
	->first();
seewhy's avatar

@LoaiDev Thanks

DB::select('select * from asks WHERE amount IN (select MIN(amount) as lowest_ask from `asks` where `product_uuid` = ? group by `shoe_size_id`)', [$this->uuid]);

The above query works, I just need a way to write it in "the eloquent way" for two reasons:

  1. I have to hydrate the model to access to its relations
  2. I am having issues with Laravel Raw queries in postgres
AlexElementarteilchen's avatar

You could split it in two queries.

The first one will get the list of lowest_ask:

$lowest_asks = DB::table('asks')
	->selectRaw('MIN(amount) AS lowest_ask')
	->where('product_uuid', $this->uuid)
	->groupBy('shoe_size_id')
	->pluck('lowest_ask')
	->toArray();

Not sure if the groupBy() will work like this because it's not part of the select statement (maybe needs some tweaking)

In the second one you can use the $lowest_ask like so:

Ask::whereIn('amount', $lowest_ask)->get();

Hope this helps!

seewhy's avatar

@AlexElementarteilchen Thanks, I was try to avoid that but till I find out how to write it in a single query. this is how I have it

Ask::whereIn('amount', Ask::selectRaw('MIN(amount) as lowest_ask')
    ->where('product_uuid', $product_id)
    ->groupBy('shoe_size_id')
  	->pluck('lowest_ask')
    ->toArray()
)->get();

Thanks again @alexelementarteilchen

Please or to participate in this conversation.