laravel updateOrCreate method laravel updateOrCreate method laravel laravel

laravel updateOrCreate method


In your use case, you should specify a second parameter. The first indicates the conditions for a match and second is used to specify which fields to update.

$newUser = \App\UserInfo::updateOrCreate([    //Add unique field combo to match here    //For example, perhaps you only want one entry per user:    'user_id'   => Auth::user()->id,],[    'about'     => $request->get('about'),    'sec_email' => $request->get('sec_email'),    'gender'    => $request->get("gender"),    'country'   => $request->get('country'),    'dob'       => $request->get('dob'),    'address'   => $request->get('address'),    'mobile'    => $request->get('cell_no')]);

Here is an example from the documentation: https://laravel.com/docs/5.4/eloquent

// 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]);


Eloquent has the method called updateOrCreate, which can be used like this example:

<?$flight = UserInfo::updateOrCreate(    [       'user_id'   => Auth::user()->id,    ],    [       'about'     => $request->get('about'),       'sec_email' => $request->get('sec_email'),       'gender'    => $request->get("gender"),       'country'   => $request->get('country'),       'dob'       => $request->get('dob'),       'address'   => $request->get('address'),       'mobile'    => $request->get('cell_no')    ],);
  1. Search by user_id could be your best way to identify your rows.
  2. It creates or updates according to the values given in the second array.

The following is the sign of the method.

/** * Create or update a record matching the attributes, and fill it with values. * * @param  array  $attributes * @param  array  $values * @return \Illuminate\Database\Eloquent\Model */public function updateOrCreate(array $attributes, array $values = [])