Challenges with Laravel’s firstOrCreate Function

The model possesses a particular attribute. If you are using an older version of Laravel, you can attain the same results with the following solutions. For the first solution, the create() method is not advisable due to the security risks associated with mass assignment. Hence, Laravel has a protection method against it and you will need to call save manually to preserve it. Alternatively, you can utilize the Facade. The second solution suggests that instead of the model, it is better to place the function in one of your controllers.


Solution:

The probable cause behind the unique key constraint error is your incorrect usage of

firstOrCreate()

. The correct query must be utilized.

$attribute = AttributeValue::firstOrCreate(
    [
        'value' => $value,
    ],
    [
        'attribute_id' => $relation->attribute_id,
        'default_order' => $next,
    ]
);

Presenting the Eloquent Builder’s

firstOrCreate()

method’s source code.

    /**
     * Get the first record matching the attributes or create it.
     *
     * @param  array  $attributes
     * @param  array  $values
     * @return IlluminateDatabaseEloquentModel|static
     */
    public function firstOrCreate(array $attributes = [], array $values = [])
    {
        if (! is_null($instance = $this->where($attributes)->first())) {
            return $instance;
        }
        return tap($this->newModelInstance($attributes + $values), function ($instance) {
            $instance->save();
        });
    }

It is evident that the translation is a rough one.

$attribute = AttributeValue::where('value', $value)->first();
if ($attribute === null) {
    $attribute = AttributeValue::create([
        'value' => $value,
        'attribute_id' => $relation->attribute_id,
        'default_order' => $next,
    ]);
}

Frequently Asked Questions

Posted in Php