How to get latest record in Laravel 9 [duplicate] - php

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;

Related

Can't get result from where condition with variables in laravel

this is how i'm trying to get the type of certificate with where condition , but still recieve
nothing from this query:
$res= student::find($student, ['typecertificate']);
$k = certificate::select('id-cer')->where('name-cer','=',$res)->get();
return $k;
Based on your comments, I'm assuming you want to retrieve the field certificateType from the latest record that was inserted in the students table.
You can achieve that without a where clause, by directly using the Eloquent Builder to retrieve only that specific field like this:
Student::latest()->first('certificateType');
But this would give you an Eloquent Collection with one element. If you just want the value (not wrapped in a collection), you can simply retrieve the latest student and get the corresponding field directly:
$certificateType = Student::latest()->first()->certificateType;
I could explain more, but your question is vague and your database schema isn't clear either, so I'd need more information on that as well as what you intend to achieve.
In any case, Laravel's documentation is often a big help: https://laravel.com/docs/9.x/eloquent#retrieving-single-models

UpdateExistingPivot for multiple ids in loop = n+1 problem. Is there another way?

There's another very similar issue with an answer that was very helpful (and I'm currently using) but causes the n+1 query problem.
I'll outline my use case. Polymorphic many to many relationship
I have:
Location model
Vendor model
User Model
Contactable (custom pivot model - still fleshing this out)
Users can be marked as contacts (aka contactables) for both Locations and Vendors.
I need to not detach contactables when dissociating them (I need a record of the fact that a User was once a contact for a location or vendor) so I don't want to detach them, I need to mark them inactive.
I'll limit the scope of this scenario to the following fields in the contactables table:
active
user_ID
contactable_type
contactable_ID
So I'm executing:
$collectionOfLocationIds = $contactDetails->locations()->getRelatedIds(); //changed to 'allRelatedIds()' in 5.4+
foreach ($collectionOfLocationIds as $locationID)
{
$contactDetails->locations()->updateExistingPivot($locationID, ['active' => 0]);
}
This runs great for most of my vendors, but some have 5k+ locations, so then I'm executing 5k+ update operations for what should really be one query. DB lives on a different server, so a few extra milliseconds add up pretty quickly...
I tried passing an array of ids to the updateExistingPivot function (it says it will take a mixed type for the id parameter) it doesn't produce an error, but it only seems to update the first id in the array. I'm not sure if this is a new bug, #Wallace Maxters mentioned that he could pass an array in 4.2, and I am still working in 5.3, but I'm wondering if anyone else has had this problem.
(Updated for clarity)
Use raw query instead of relationship.
I don't exactly understand which rows you want to inactive.
So lets think you want to inactive contactable for a particualar user.
If its not, change it to whatever where().
DB::table('contactable')->where('user_id', $user_id)
->update(['active' => 0]);
this will only execute one query.

Laravel. I can't read the data from the column

I have a problem.
Needs to get the first date of creation of data in the table by the currently logged in user.
Working example:
$howMuchIPlay = Game::all('user_id')->where('user_id', '=', Auth::user()->id)->count();
Not working example:
$firstVoteInGame = Game::all('created_at')->first()->where('user_id','=', Auth::user()->id);
When I use count() function I get value 38. This is all the rows for the user, but I want to get only the earliest (first). How can I do this?
Sorry for my english and thank you in advance for help.
$firstVoteInGame = Game::where('user_id', '=', Auth::user()->id)->oldest()->first();
This will get the earliest (oldest) record from the current authenticated user.
You got the order wrong.
You should first limit by user Id.
Then order by created at in descending order so oldest is on top. Or if you want the newest, order by 'desc' instead of 'asc'
Then get the first.
Game::where('user_id','=', Auth::user()->id)->orderBy('created_at','asc')->first();
What you did was:
Get all records from database in a collection.
get first possible record from collection at index 0
limit a model object by a where query(it would fail here since you were in a model object, not a collection or query builder instance);
Your not working example, $firstVoteInGame = Game::all('created_at')->first()->where('user_id','=', Auth::user()->id);, starts off with Game::all('created_at').
What this means is that all Games are returned, but these are limited to the 'created_at' column only (see the documentation here).
Since you're limiting your result to the 'created_at' column, Eloquent will now not be able to compare the 'user_id' columns to the authenticated user id.
In addition, even if you were to select all columns (by performing Game::all()), you are calling ->first() after which you only have the first row remaining.
You say you want to
get the first date of creation of data in the table by the currently logged in user.
This would thus by done by:
$firstVoteInGame = Game::where('user_id', Auth::user()->id)->orderBy('created_at','asc')->first('created_at');
Why you use 'created_at' for ordering as easy/correct way is use primary key, Because you can just do:
$firstVoteInGame = Game::where('user_id','=', Auth::user()->id)->orderBy('id', 'desc')->first();
You can try, if you still want 'created_at':
$firstVoteInGame = Game::where('user_id','=', Auth::user()->id)->orderBy('created_at', 'desc')->first();
TIP
- The Eloquent all method will return all of the results in the model's table so avoid to use it with first method

Laravel inRandomOrder repeat twice with pagination

I have the code:
$products = Product::whereIn('id_principal_category', $array)->inRandomOrder()->paginate(6);
It sometimes shows me a repeated record.
I have read that I must use whereNotIn, the problem is that it can work if it just one time... but how can i do that if does it have a paginator? because i dont know which the repeated records are and i cant use whereNotIn.. so my question is how can I do that inRandomOrder does not show a repeated record with paginator?
Thanks
See if unique() method helps.
$products = Product::whereIn('id_principal_category', $array)->unique()->inRandomOrder()->paginate(6);
You can't use random ordering with pagination ,mysql cannot track the rows for each visitor .
I quoted those lines from Chris Henry's answer
Solution 1
Pick from a number of existing columns that already indexed for being sorted on. This can include created on, modified timestamps.
Solution 2
You could have an additional column that stores a random number for sorting. It should be indexed, obviously. Periodically, run the following query;
UPDATE table SET rand_col = RAND();

Laravel - Execute function before query is fired

is there a way for Eloquent/raw queries to execute a function before a query is fired? It would also be nice if I could extend the functionality to pass a parameter if the function should be run before or not. Depending on the outcome of the function (true/false) the query shouldn't be executed.
I would be nice to use the principal of "DB::listen", but I'm not sure if I can stop or run the query from within this function.
The reason for this is that I would like to build a little data warehouse myself for permanently saving results to a warehouse (db) and not query a huge database all the time.
The method I'm would like to use is to create a hash of a query, check if the hash exists in the warehouse. If it exists, then the value is returned. If not the query is executed and the output is saved together with the hash into the warehouse.
Any ideas?
///// EDIT /////
I should clarify, that I would like to access the queries and update the value if the calculated value needs to be updated. i.e.: Number of cars in december: While I'm in december, I need to keep updating the value every so often. So I store the executed query in the db and just retrieve it, run it and then update the value.
//// EDIT 2 /////
Github: https://github.com/khwerhahn/datawarehouselibrary/blob/master/DataWareHouseLib.php
What I would like to achieve is to hook into Laravels query/Eloquent logic and use the data warehouse logic in the background.
Maybe something like this:
$invalid_until = '2014-12-31 23:59:59'; // date until query needs to be updated every ten minutes
$cars = Cars::where('sales_month', '=', 12)->dw($invalid_until)->get();
If the dw($date_parameter) is added I would like Laravel to execute the data warehouse logic in the background and if found in the db then not execute the query again.
You don't need to use events to accomplish this. From the 4.2 docs:
Caching Queries
You may easily cache the results of a query using the remember method:
$users = DB::table('users')->remember(10)->get();
In this example, the results of the query will be cached for ten
minutes. While the results are cached, the query will not be run
against the database, and the results will be loaded from the default
cache driver specified for your application.
http://laravel.com/docs/4.2/queries#caching-queries
You can also use this for Eloquent objects,
eg: User::where($condition)->remember(60)->get()
I get what you're trying to do, but as I view it (I might not still be getting it right, though) you still can get away with using rememberForever() (if you don't want a specific time limit)
So, let's pretend you have a Cars table.
$cars = Cars::where('sales_month', '=', 12)->rememberForever()->get();
To work around the problem of deleting the cache, you can assign a key to the caching method, and then retrievit by that key. Now, the above query becomes:
$cars = Cars::where('sales_month', '=', 12)->rememberForever('cars')->get();
Every time you run that query you will be getting the same results, first time from the DB, all the others from the cache.
Now you say you're going to update the table, and you want to reset the cache, right?
So, run your update, then forget() the Cache with the cars index:
// Update query
Cache::forget('cars');
Your next call to the Cars query will issue a new resultset, and it will be cached. In case you're wondering, the remember() and rememberForever() are methods of the QueryBuilder class that use the same Cache class you can see in the docs in its own section.
Alternatively, in fact, you could also use the Cache class directly (it gives you a better control):
if (null == $cars= Cache::get('cars')) {
$cars = Cars::where('sales_month', '=', 12)->get();
Cache::forever('cars', $cars);
}
By overriding the method runSelect exsists in Illuminate\Database\Query\Builder that runs in every select query in Laravel.
see this package:
https://github.com/TheGeekyM/caching-queries

Categories