Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an empty Laravel model instance without attributes, but still get the id

Basically, I'm creating an Article instance:

$article = new Article();
//Returns null
$id = $article->id();

This however returns an empty object. What I would like to do is create an article and also get its id before doing:

$article->save();

Trying to create an article doesn't work, because it requires providing values or having default ones:

$article = Article::create();

The approach I'm thinking about is doing:

$latest_id = Article::latest()->first()->id;

But I'm not sure if it's the right one, or if there is a better method.

like image 483
RandomBeginner Avatar asked Sep 17 '25 09:09

RandomBeginner


2 Answers

The id is the value of the id column in data-base, and cause you did not save yet, there is nothing in data-base (and you can not get it).

I guess you need to do some tasks which could in some point fail or get cancelled, for which case there is a workaround, like:

DB::beginTransaction();

try {
    $article = new Article();
    $article->fields = 'example';
    $article->save();

    // Anything needing ID here...

    DB::commit();
} catch (\Exception $e) {
    DB::rollback();
    // Handle or re-throw:
    throw $e;
}
like image 153
Top-Master Avatar answered Sep 18 '25 23:09

Top-Master


You can't get the ID of a Object / Model what you have not saved yet.

In this case the ID does not exist, you can find the latest ID and increase this ID by one, but then you could run in some race-condition, when another script what is also adding a new element to this Table is faster, then you have the wrong ID you save later.

If you need the ID to store References for this Model, the correct way would be to save the model first, and then save the references.

If you need the ID to save a file containing the ID in the filename, what you save then as text in the database you could first save the Model (to retrieve an ID), and then save the model with the missing informations again.

like image 24
brokedid Avatar answered Sep 18 '25 22:09

brokedid