DMS-KH
DMS-KH

Reputation: 2797

how to get last id when a row was insert in laravel eloquent in Model

I've used setNotification method of model by initial data from Controller within a variable $data as array. I have used self:: in this method instead of used table or Notification::save() or $obj->save(). by this way I don't know how to get Id which the last id after insert was done in laravel because I used $this->attributes that it is the protected variable in Model.

class Notification extends Model
{

    protected $table = 'notification';
    public $timestamps = true;
    private $_data = false;


    public function setNotification($data)
    {
        if (is_array($data)) {
            $this->attributes = $data;
            self::save();
        }
    }
}

Upvotes: 1

Views: 593

Answers (2)

Giedrius Kiršys
Giedrius Kiršys

Reputation: 5314

I suggest You to use create method instead and return created object, so then You can access id property.

public function setNotification($data)
{
   if (is_array($data)) {
        return $this->create($data);
   }

   return null;
}

Upvotes: 1

Alexey Mezenin
Alexey Mezenin

Reputation: 163948

Try something like $this->attributes[id] after save() is executed.

Upvotes: 1

Related Questions