Skip to content
Advertisement

Laravel Eloquent – get last insert of related model

I have a relationship between two models: Terminal and terminalRent.

A Terminal can have many terminalRents. I want to get the last Rent for a specific Terminal.

$lastRent = Terminal::with('terminalRent')->where('id', $id)->orderBy('id', 'desc')->first();

When using where() it will reflect those on the Modal hoewever I want to get the last record for terminalRent in relation to the specific terminal. $id is the Id of the terminal and the tables are connected like this:

Terminal
----
ID


terminalRent
-----
ID
terminal_id <--- this is the foreign key for the ID of the Terminal Table

Advertisement

Answer

If the relationship between Terminal and Terminal rent is hasMany you can do something like:

$lastRented = $lastRent->terminalRent->last();

Ensure you have the last rented via dd($lastRented);

Let me know how you get on

Edit: If this gives you the incorrect instance of terminalRent try first(); I can’t remember how Eloquent orders eagerlaoded relationships by default.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement