Laravel Eloquent combine Model::forceCreate and Model::firstOrCreate

2.7k views Asked by At

With Laravel & Eloquent, I'd like to :

  • Create a model, unless it already exists into the database (like Model::firstOrCreate allows)
  • At the same time, pass it a few attributes, including some which are not listed in the $fillable array of the model (like Model::forceCreate allows).

But how do I combine the capacities of firstOrCreate and forceCreate? Apparently, Model::forceFirstOrCreate doesn't exist!

1

There are 1 answers

2
Joseph Silber On BEST ANSWER

Use the unguarded method:

$model = Model::unguarded(function() {
    return Model::firstOrCreate($attributes);
});