John Evans Solachuk
John Evans Solachuk

Reputation: 2105

Why is laravel's updateOrCreate creating new records instead of updating?

Code

Entry::updateOrCreate([
    'intern_id'=>$intern['id'],
    'created_at'=>Carbon::parse($input['date'])
    ],[
    'company_id'=>$intern['supervisor']['company']['id'],
    'content'=>$input['text']
]);

I'm using this code to try updating/creating a new record. It's suppose to matche intern_id and create_at column first. If found, then it creates a new one. However, it seems like it is always creating a new one and when it creates a new one, the company_id and intern_id column is set to 0 instead of the original value.

Note: intern_id or created_at are not PK columns. Note2: created_at is a Date type, not DateTime

Upvotes: 3

Views: 8000

Answers (3)

stanley mbote
stanley mbote

Reputation: 1306

I had the same issue where it was only creating a record but it wasn't being updated in the event that the record exists.

The issue is that to allow for the mass assignment on the update you need to add the fields to be updated as fillable in your model.

In your Entry model you can have something close to this :

   protected $fillable = [

           'company_id',
           'content',

           ];

I hope this helps in sorting out the issue.

Upvotes: 0

user7027429
user7027429

Reputation:

Entry::updateOrCreate(
    [
        'intern_id' => $intern['id'],
    ],
    [
        'created_at' => Carbon::parse($input['date'])
            'company_id' => $intern['supervisor']['company']['id'],
        'content' => $input['text']
    ]
);

because first argument array searched for first time found one line with date and second line found other date deferent -----------

// If there's a flight from Oakland to San Diego, set the price to $99. // If no matching model exists, create one.

$flight = App\Flight::updateOrCreate(
    ['departure' => 'Oakland', 'destination' => 'San Diego'],
    ['price' => 99]
);

Upvotes: 3

Ariful Haque
Ariful Haque

Reputation: 3750

Use this code

Entry::updateOrCreate(['intern_id'=>$intern['id']],
    [
        'created_at'=>Carbon::parse($input['date']),
        'company_id'=> $intern['supervisor']['company']['id'],
        'content'=>$input['text']
    ]);

I believe this will work.

updateOrCreate() function of Model Abstract Class takes 2 parameters, but your parameter passing is breaking.

/**
     * Create or update a record matching the attributes, and fill it with values.
     *
     * @param  array  $attributes
     * @param  array  $values
     * @return static
     */
    public static function updateOrCreate(array $attributes, array $values = array())
    {
        $instance = static::firstOrNew($attributes);

        $instance->fill($values)->save();

        return $instance;
    }

Upvotes: 10

Related Questions