Reputation: 83
I want to insert a simple menu in my database, and the menu also supports a thumbnail. Before I insert the menu in my database, I want to grab the last incremented id(that was unknown) from MySQL for naming my thumbnail with the unique id.
I can grab the last id if the table has at least one row.
// last insert id
$last_id = App\Menu::get()->last()->id;
// or // last insert id
$last_id = App\Menu::selectRaw('MAX(id) AS latest_id')->get();
If there is no data, then the above code should return null. My question is how can I get the last auto incremented id that will be generated by MySQL.
Upvotes: 0
Views: 274
Reputation: 383
I agree with @ajafari.
The better approach is to create the menu first and then name the thumbnail.
It looks like this:
$menu = new Menu(['column_name' => value, etc ...]);
$menu->save();
//Now you have access to the latest id of the menu in $menu->id
Hope that helps!
Upvotes: 0
Reputation: 193
In my opinion, change your strategy. The better way is to name your thumbnail after getting the last insert id. As you know PHP is a request base language and if you will have several requests which want to do this job at the same time you would encounter serious problems with conflict ids.
Upvotes: 1