如何在模型中以lalovel eloquent插入行时获取最后一个id

时间:2016-04-06 04:07:54

标签: laravel laravel-5 eloquent

我在变量 $ data 中使用Controller的初始数据作为数组,使用了 setNotification 模型方法。我在这种方法中使用了self ::而不是使用表格或 Notification :: save() $ obj-> save()。通过这种方式我不知道如何获得Id插入后的最后一个id在laravel完成,因为我使用了$ this->属性,它是模型中的受保护变量。

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();
        }
    }
}

2 个答案:

答案 0 :(得分:1)

执行$this->attributes[id]后尝试save()之类的内容。

答案 1 :(得分:1)

我建议您改用create方法并返回创建的对象,这样就可以访问id属性。

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

   return null;
}