Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 983
xTheWolf Avatar asked Aug 12 '16 07:08

xTheWolf


People also ask

What is orderBy in Laravel?

The Laravel Orderby works by simply sorting the results of the query. So if the column has a list of 20 data, it can sort the list by the parameter provided. One can also create an order in an ascending or a Descending Order. By Ascending Order: $users = DB::table('users')->orderBy('name', 'asc')->get();

Is eloquent an ORM?

Eloquent is an object relational mapper (ORM) that is included by default within the Laravel framework. An ORM is software that facilitates handling database records by representing data as objects, working as a layer of abstraction on top of the database engine used to store an application's data.

What is advantage of eloquent in Laravel?

Eloquent is an ORM, which means can automatically handle the relationships of your models for you. You can retrieve related models without writing complex queries. You can even retrieve database information without any kind of database knowledge at all.


2 Answers

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.

like image 117
ExohJosh Avatar answered Oct 10 '22 03:10

ExohJosh


@Parithiban Solution is very useful but this function run one query two times

for better performance try this

$lastRent =  Terminal::with(['terminalRent' => function ($query) { 
  return $query->orderBy('id', 'desc')->limit(1);
}]);
like image 23
MirVan Avatar answered Oct 10 '22 01:10

MirVan