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

MartinDevNow's avatar

Raw Query but Map to my Model??

Hello! I have a table of inventory levels. It integrates with an RFID reader that pushes info to my database mapped by the (basically) id, pusher_id, item_count, and created_at.

I use the following line to get an array of the latest inventory levels by customer.

        $inventories = DB::select(DB::raw('SELECT inv_1.*
FROM inventories inv_1
WHERE inv_1.created_at = (
  SELECT MAX(inv_2.created_at)
  FROM inventories inv_2
  WHERE inv_2.pusher_id = inv_1.pusher_id
  ) AND client_id = '. $this->user->client_id .';'));

The Problem is, this is returned as an array when I would like it as an eloquent model collection so I can utilize the relationships built in.

How can I rewrite this query using Inventory::...

Thanks!

0 likes
4 replies
Jeffberry's avatar
Level 4

Take a look at the hydrate and hydrateRaw methods on your eloquent model. Should do what you want :)

3 likes
mikebronner's avatar

Why not get it through the relationships, something like this perhaps:

$client = $this->user->client;
$client->load('inventories'); // if not already loaded
$maxInventoryDate = DB::table('inventories')->where('client_id', $client->id)->max('created_at');
$inventories = client->inventories->where('created_at', $maxInventoryDate)->get();

There probably is a better way to structure it so that there is only one query, i.e. through a join, but I think this might at least get you on the right track? Let us know how it goes. :)

Update: @Jeffberry 's response is probably the simplest solution. You might have to load the relationships once hydrated, though. This will likely cause additional database queries, but I'm not sure on the absolute performance metrics. With the above solution you could populate the relationships from the get-go using the ->with('relationship') method.

Please or to participate in this conversation.