Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: static::create vs DB:insert

If I use the following code snippet in my model it inserts the data:

$instance = DB::table('users')->insert(compact('email', 'username'));

But if I do this instead:

$instance = static::create(compact('email', 'username'));

It inserts null, but created_at and updated_at are inserted.

like image 206
Prezioso Avatar asked Nov 22 '22 04:11

Prezioso


1 Answers

Laravel's created_at/updated_at are part of Illuminate\Database\Eloquent\Model. A raw DB::table query builder isn't an Eloquent model and thus doesn't have those automatic parameters.

NULL data is being inserted in the Eloquent query because Eloquent has a $fillable parameter you need to define. This parameter sets which columns can be mass-assigned. Laravel strips attributes not in this array when you do a fill, create, or otherwise instantiate a new object. In your model, you'd want:

class User extends Eloquent {
  protected $fillable = ['email', 'username'];
}
like image 67
ceejayoz Avatar answered Dec 04 '22 03:12

ceejayoz