Answer the question
In order to leave comments, you need to log in
How to get the ID of a newly created post (Laravel)?
Good day and good mood everyone!
php has a mysql_insert_id() function that is used right after the query to get the ID of the last record
. I have two questions:
1. What is the probability that this function will return the wrong ID? (if after my insertion someone else managed to add a record)
or will this function return the last added record only for the CURRENT connection? Please shed some light for now.
2. How to get the latest ID in Laravel using Eloquent? And again, what is the probability that this function will return the wrong ID? (if after my insertion someone else managed to add a record)
Thank you!
Answer the question
In order to leave comments, you need to log in
$model = Product::create($attributes);
var_dump($model->id); // prints inserted id
$model = new Product($attributes);
$model->save();
var_dump($model->id); // prints inserted id
If the table has an auto-increment ID, use the insertGetId() method to insert a record and get its ID:
$id = DB::table('users')->insertGetId(
['email' => '[email protected]', 'votes' => 0]
);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question