I would like to retrieve the last file inserted into my table. I know that the method first() exists and provides you with the first file in the table but I don't know how to get the last insert.
You'll need to order by the same field you're ordering by now, but descending.
As an example, if you have a time stamp when the upload was done called upload_time, you'd do something like this;
For Pre-Laravel 4
return DB::table('files')->order_by('upload_time', 'desc')->first();
For Laravel 4 and onwards
return DB::table('files')->orderBy('upload_time', 'desc')->first();
For Laravel 5.7 and onwards
return DB::table('files')->latest('upload_time')->first();
This will order the rows in the files table by upload time, descending order, and take the first one. This will be the latest uploaded file.
Use the latest scope provided by Laravel out of the box.
Model::latest()->first();
That way you're not retrieving all the records. A nicer shortcut to orderBy.
You never mentioned whether you are using Eloquent, Laravel's default ORM or not. In case you are, let's say you want to get the latest entry of a User table, by created_at, you probably could do as follow:
User::orderBy('created_at', 'desc')->first();
First it orders users by created_at field, descendingly, and then it takes the first record of the result.
That will return you an instance of the User object, not a collection. Of course, to make use of this alternative, you got to have a User model, extending Eloquent class. This may sound a bit confusing, but it's really easy to get started and ORM can be really helpful.
For more information, check out the official documentation which is pretty rich and well detailed.
To get last record details
Model::all()->last(); or
Model::orderBy('id', 'desc')->first();
To get last record id
Model::all()->last()->id; or
Model::orderBy('id', 'desc')->first()->id;
Many answers and some where I don't quite agree. So I will summarise again with my comments.
In case you have just created a new object.
By default, when you create a new object, Laravel returns the new object.
$lastCreatedModel = $model->create($dataArray);
dd($lastCreatedModel); // will output the new output
echo $lastCreatedModel->key; // will output the value from the last created Object
Then there is the approach to combine the methods all() with (last()and first()) without a condition.
Very bad! Don't do that!
Model::get()->last();` // the most recent entry
Model::all()->last();` // the most recent entry
Model::get()->first();` // the oldest entry
Model::all()->first();` // the oldest entry
Which is basically the wrong approach! You get() all() the records, and in some cases that can be 200,000 or more, and then pick out just one row. Not good! Imagine your site is getting traffic from Facebook and then a query like that. In one month that would probably mean the CO² emissions of a city like Paris in a year. Because the servers have to work unnecessarily hard. So forget this approach and if you find it in your code, replace it/rewrite it. Maybe you don't notice it with 100 data sets but with 1000 and more it can be noticeable.
Very good would be:
Model::orderBy('id', 'desc')->last(); // the most recent record
Model::latest('id')->first(); // the most recent record
Model::latest('id')->limit(1)->get(); // the most recent record
Model::orderBy('id', 'desc')->limit(1)->get(); // the most recent entry
Model::orderBy('id', 'desc')->first(); // the most recent entry
Model::orderBy('id', 'asc')->first(); // the oldest entry
Model::orderBy('id', 'asc')->limit(1)->get(); // the oldest entry
Model::orderBy('id', 'asc')->first(); // the oldest entry
If orderBy is used in this context, the primarykey should always be used as a basis and not create_at.
Laravel collections has method last
Model::all() -> last(); // last element
Model::all() -> last() -> pluck('name'); // extract value from name field.
This is the best way to do it.
You can use the latest scope provided by Laravel with the field you would like to filter, let's say it'll be ordered by ID, then:
Model::latest('id')->first();
So in this way, you can avoid ordering by created_at field by default at Laravel.
Try this :
Model::latest()->get();
Don't use Model::latest()->first(); because if your collection has multiple rows created at the same timestamp (this will happen when you use database transaction DB::beginTransaction(); and DB::commit()) then the first row of the collection will be returned and obviously this will not be the last row.
Suppose row with id 11, 12, 13 are created using transaction then all of them will have the same timestamp so what you will get by Model::latest()->first(); is the row with id: 11.
To get the last record details, use the code below:
Model::where('field', 'value')->get()->last()
Another fancy way to do it in Laravel 6.x (Unsure but must work for 5.x aswell) :
DB::table('your_table')->get()->last();
You can access fields too :
DB::table('your_table')->get()->last()->id;
Honestly this was SO frustrating I almost had to go through the entire collection of answers here to find out that most of them weren't doing what I wanted. In fact I only wanted to display to the browser the following:
The last row ever created on my table
Just 1 resource
I wasn't looking to ordering a set of resources and order that list through in a descending fashion, the below line of code was what worked for me on a Laravel 8 project.
Model::latest()->limit(1)->get();
Use Model::where('user_id', $user_id)->latest()->get()->first();
it will return only one record, if not find, it will return null.
Hope this will help.
Model($where)->get()->last()->id
For laravel 8:
Model::orderBy('id', 'desc')->withTrashed()->take(1)->first()->id
The resulting sql query:
Model::orderBy('id', 'desc')->withTrashed()->take(1)->toSql()
select * from "timetables" order by "id" desc limit 1
If you are looking for the actual row that you just inserted with Laravel 3 and 4 when you perform a save or create action on a new model like:
$user->save();
-or-
$user = User::create(array('email' => 'example#gmail.com'));
then the inserted model instance will be returned and can be used for further action such as redirecting to the profile page of the user just created.
Looking for the last inserted record works on low volume system will work almost all of the time but if you ever have to inserts go in at the same time you can end up querying to find the wrong record. This can really become a problem in a transactional system where multiple tables need updated.
Somehow all the above doesn't seem to work for me in laravel 5.3,
so i solved my own problem using:
Model::where('user_id', '=', $user_id)->orderBy('created_at', 'desc')->get();
hope am able to bail someone out.
be aware that last(), latest() are not deterministic if you are looking for a sequential or event/ordered record. The last/recent records can have the exact same created_at timestamp, and which you get back is not deterministic. So do orderBy(id|foo)->first(). Other ideas/suggestions on how to be deterministic are welcome.
You just need to retrive data and reverse them you will get your desire record let i explain code for laravel 9
return DB::table('files')->orderBy('upload_time', 'desc')->first();
and if you want no. of x last result
return DB::table('files')->orderBy('upload_time', 'desc')->limit(x)->get();
If the table has date field, this(User::orderBy('created_at', 'desc')->first();) is the best solution, I think.
But there is no date field, Model ::orderBy('id', 'desc')->first()->id; is the best solution, I am sure.
you can use this functions using eloquent :
Model::latest()->take(1)->get();
With pdo we can get the last inserted id in the docs
PDO lastInserted
Process
use Illuminate\Support\Facades\DB;
// ...
$pdo = DB::getPdo();
$id = $pdo->lastInsertId();
echo $id;
I am trying to get a user with his posts in laravel, so far I have tried to use the following line
User::findOrFail($user_id)->with('posts')->first();
But I am getting the first user on the table regardless of what the user ID specified is.
I have tried to dd the user_id and it's working fine, (getting the user_id from the route).
So far the result I am getting is if the user id is x and the first user in the table has an id of 1 I get the info of user id 1 and his posts.
Thanks in advance!
You have your methods in the wrong order.
findOrFail executes the query immediately, which returns the User record for $user_id.
Chaining that to ->with() will start a new query.
Finally, calling ->first() returns the first User from the database.
Adjust your query as such:
User::with('posts')->findOrFail($user_id);
findOrFailand first will give you the User Object but you have to decide witch function you will use.
If you use Routemodel Binding then you can use:
User::with('posts')->first(); or User::load('posts');
If you dont use routemodel Binding you can use findOrFail like that:
User::with('posts')->findOrFail($user_id);
I'm trying to get the ID from an INSERT query with CAKEPHP.
In this case I'm not working with the Model itself so I'm not using the following code:
$this->ModelName->save($data);
//Then...
$this->ModelName->getInsertID();
$this->ModelName->getLastInsertID();
I'm just using
$this->query("INSERT.......");
How can I get the Inserted ID with CakePHP without referencing the model?
I think that the problem is that the query is beeing cached.
If you see the logs the query isn't even been executed (I tried your code)
try this instead
$this->query("SELECT LAST_INSERT_ID();" , false);
see manual
http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#model-query
$this->query('SELECT LAST_INSERT_ID()');
See LAST_INSERT_ID() in the MySQL documentation.
my userlisting provides link to edit users and update profile as when one clicks the screen name of the user then it goes to profile update view with the id of corresponding user:
//url:
localhost/damcombd/admin/userprofile/userupdate/3
The form loads nice and address bar and on mouse over status bar both shows the link as above
but in reality in the controller if i pull something with this id say from user model it just goes to the first record or the id 1.. and doing it all the way.. try as i might!
What could be the reason? Checked for any hardcoded ids too.. but that's not the case..
//with this one too I create a row and get it back like:
$this->commonmodel->create_and_get($table,$data){
$this->db->insert($table,$data);
$lastid=$this->db->insert_id();
$getback=$this->db->get($table,array('id'=>$lastid))->result_array();
return $getback[0];
But what it return every time the first row.. I dont know like the userprofile updating above this one also shitting around.. Is it a bug or something..I dont get it at all..try as I might:( :( Please do something..
This may be because:
a) In your routes you're specifying an id it's taking all the time:
b) Your controller is taking a wrong id
c) Your model is executing a wrong query.
What I'd do: Check you have in the routes applocation/config/routes a sentence with
$routes['admin/userprofile/userupdate/(:num)'] = 'admin/userprofile/userupdate/$1'
Maybe you forgot the $ before the 1, ;P.
Then, check the value you're sending, for being sure is the right id, after receiving the POST/GET value, print it and check if this value is the expected one (you're editing user 2, so you get id 2 and so on).
If the value is correct, check what are you retrieving from the database. In your model, you can write:
echo $this->db->last_query();
and check what SQL query is executing. Just do as I wrote you above, and tell us what happens, :D
The second problem I mentioned is solved when I used
$this->db->get_where($table,array('id'=>$lastid));
//actually for get the above line would have been false syntax..
I think I will I figure next one out too...
My First problem is solved too... That exact way actually..
to describe it a bit so that some one might be helped..
//If u use
$obj=$this->db->get($table,array('id'=>$lastid))->result_array(); //here then
// it will actually do a simple get all operation and returning:
return $obj[0] //will obviously return the very first row..try as u might.
//so for querying with id always use:
$this->db->get_where();
My controller needs to create/save one or more records by looping over the request data it receives and creating corresponding records. You may be wondering: why not just use saveAll() and save them all at once. The short answer is that certain records need to reference the ID of other records created in the same loop (and those IDs don't exist yet).
My loop creates the first record successfully, subsequent iterations of the loop are unable to "see" that newly created record when I use find(). If I echo the returned array, results are there, but the newly created one is missing. Why? Is CakePHP's magic making the new record unavailable due to some sort of caching?
Here is my code that doesn't include the newest record:
$newest_parent_question = $this->Question->find('first', array(
'conditions'=>array('Question.perm_id'=>$parent_question['Question']['perm_id']),
'order' => array('Question.created DESC')
)
);
However, the new record IS returned with this:
$newest_parent_question = $this->Question->find('all');
There's something wrong with your query.
Likely the $parent_question['Question']['perm_id'] is wrong. There's nothing CakePHP will do that would make your record un-find-able.
Just debug your variables to make sure you're building the correct query with the correct id, and you'll be good to go.
(without seeing the actual way you're building the id, it's impossible to help beyond that)