F
F
freelancer0072016-05-11 18:08:14
MySQL
freelancer007, 2016-05-11 18:08:14

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

3 answer(s)
M
Mikhail Osher, 2016-05-11
@freelancer007

$model = Product::create($attributes);
var_dump($model->id); // prints inserted id

$model = new Product($attributes);
$model->save();
var_dump($model->id); // prints inserted id

O
otjog, 2018-02-02
@otjog

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]
);

A
Andrey, 2016-05-11
@VladimirAndreev

well, the model created/saved, the model said everything is fine?
I see no logical reason why its ID is not filled with the ID assigned by the base. seems to be standard behavior...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question