Skip to content
Advertisement

laravel, use of updateOrCreate inside forloop

I want to use updateOrCreate in order to prevent duplicate I have stores and need to store for every store its working hour (days, open time, close time, available)

Day Available Open Close

Monday [checkbox] [input] [input]

Tuesday [checkbox] [input] [input]

Wednesday [checkbox] [input] [input]

but I still get duplicate when inserting new values

Model:

protected $table = 'storedays';
protected $fillable = ['storeinfo_id', 'day_id','open_time','close_time','available'];
protected $primaryKey = 'id';

Controller:

public function store(Request $request)
{
    $store_id=$request->storeinfo_id;
    $open_time = $request->input('open_time');
    $close_time = $request->input('close_time');
   $available=$request->input('available');

        foreach ($request->input('day_id') as $key => $value) {
            if ( ! isset($available[$key])) {
               $available[$key] = 0;
            }
            else
            {
                $available[$key] = 1;
            }


            Storeday::updateOrCreate([
                'storeinfo_id' => $store_id,
                'day_id' => $value,
                'open_time' => $open_time[$key],
                'close_time' => $close_time[$key],
                'available' => $available[$key],
                

            ]);
        }

    return response()->json(['data' => trans('message.success')]);
}

Advertisement

Answer

updateOrCreate function requires 2 params, match conditions and extra values. You need to change it to following:

Storeday::updateOrCreate([
        'storeinfo_id' => $store_id,
        'day_id' => $value,
    ],[
        'open_time' => $open_time[$key],
        'close_time' => $close_time[$key],
        'available' => $available[$key],
]);

What will the line do?

First it will look if there is an entry in table for the store id and day id. If not, it will create a new row.

You can learn more about the updateOrCreate function here.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement