How To Use The UpdateOrCreate Method In Laravel Eloquent

Here is an example of how to use the updateOrCreate method in Laravel Eloquent

PHP

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    public function updateOrCreate($attributes, $conditions = [])
    {
        $model = $this->where($conditions)->first();

        if ($model) {
            $model->update($attributes);
        } else {
            $this->create($attributes);
        }

        return $model;
    }
}

The updateOrCreate method takes two arguments:

  • The first argument is an array of attributes to update or create.
  • The second argument is an array of conditions that the model must match.

If a model matching the conditions exists, the updateOrCreate method will update the model with the given attributes. Otherwise, it will create a new model with the given attributes.

In this example, we are using the updateOrCreate method to update the user’s name if the user exists, or create a new user if the user does not exist.

Click for more posts like this.

Leave a Reply