Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel model ID null after save (ID is incrementing)

I have a save method where I do validation, create a model and save it. Later in the save method I try and access the ID of the model and it's NULL.

Schema:

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->increments('id');
        $table->string('title');
        $table->string('body');
        //and other fields that aren't important right now
        $table->timestamps();
    });
}

Save method:

public function savePost(Request $request) {

    $this->validate($request, [
        //some validation happens here
    ]);

    $post = new Post();
    $title = $request->input('title');
    $body = $request->input('body');

    $post->title = $title;
    $post->body = $body;

    $post->save();

    //I later try to access the $post->id here and it's still NULL.
    var_dump($post->id);//NULL
}

In MySQL the ID is being set (just an auto incrementing unsigned integer) - it seems like it gets set after the savePost method is complete.

I thought that after $post->save() was complete, the model's ID would be set - but that seems to not be the case. How can I access the model's ID from the same method where I save() it? Or have I made a mistake somewhere?

Laravel Framework version is 5.3.26

Edit: just to clarify: the model (including the auto incrementing PK) is being stored in MySQL, I'm just not able to access the model's id in the same method that I save it.

like image 438
Chris Avatar asked Oct 28 '25 17:10

Chris


2 Answers

Figured it out:

I ran into this issue when switching from a string PK to an auto incrementing unsigned int.

I still had public $incrementing = false; in the Post model, which explains this issue. Switching to $incrementing = true solved the problem.

like image 184
Chris Avatar answered Oct 31 '25 07:10

Chris


For other developers who are using Pivot/Junction table, if your model is extending Pivot instead of Model then this is why.

As @noob mentioned, You've to enable public $incrementing = true; manually or just extend Model instead.

like image 41
Mo Kawsara Avatar answered Oct 31 '25 08:10

Mo Kawsara