Retrieve created model ID in laravel observer

Viewed 338

i've registered an observer on my Client model.

Why is $client->id null? Shouldn't the freshly created model ID be available to read?

What can i do to retrieve the last created Client ID? ID is set as fillable in model Client, so i don't understand what the problem might be. Thanks.

<?php

namespace App\Observers;

use App\Models\Client;
use App\Models\SampleModel;

class ClientObserver
{
    /**
     * Handle the Client "created" event.
     *
     * @param  \App\Models\Client  $client
     * @return void
     */
    public function created(Client $client)
    {
        $model_to_create = new SampleModel();
        $model_to_create->id_client = $client->id;
        //other stuff to save in model
        $model->save();
    }
1 Answers

You should have created the Observer without reference to your model, if the laravel does not know which model is, the $client always gonna return null.

Related