Skip to content
Advertisement

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

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!

Advertisement

Answer

Use the unguarded method:

$model = Model::unguarded(function() {
    return Model::firstOrCreate($attributes);
});
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement