Use a Closure with updateOrInsert() in Laravel 11.10

This week, the Laravel team released v11.10, with the ability to pass a callback to updateOrInsert, support for soft-deleted models with explicit route model binding, and more.

Allow Passing a Callback to updateOrInsert()

Mark Eriksson contributed the ability to pass a callback as the second argument to the updateOrInsert() query builder method. Within the callback, the boolean $exists variable is passed so you can write logic to update specific columns based on whether the record exists or not:

DB::table('users')->updateOrInsert(
  ['user_id' => $user_id],
  function ($exists) use ($data) {
    if ($exists) {
      return [
        'name' => $data['name'],
        'email' => $data['email'],
      ];
    }

    return [
      'name' => $data['name'],
      'email' => $data['email'],
      'optional_column' => $data['foobar'],
    ];
  }
);

See Pull Request #51566 for full implementation details.

Support Soft-deleted Models When Using Explicit Route Model Binding

Graham Bradley added support for soft-deleted models when using explicit route model binding:

This PR allows the resolution of soft-deleted models when using Laravel's explicit route-model binding feature.

It allows developers to use explicit route-model binding without having to customise the resolution logic when dealing with soft-deleted models. To do so it uses the same withTrashed() method as implicit binding.

// Before
Route::get('/users/{user}', ...);
Route::bind('user', function (string $value) {
    return User::where('id', $value)->withTrashed()->firstOrFail();
});

// After
Route::get('/users/{user}', ...)->withTrashed();
Route::model('user', User::class);

See Pull Request #51651 for full implementation details.

Allow Setting Resend API Key in Mailer Config

@riasvdv contributed setting the Resend API key directly in the mailer config instead of just the services config. See Pull Request #51618 for more details.

Release notes

You can see the complete list of new features and updates below and the diff between 11.9.0 and 11.10.0 on GitHub. The following release notes are directly from the changelog:

v11.10.0


The post Use a Closure with updateOrInsert() in Laravel 11.10 appeared first on Laravel News.

Join the Laravel Newsletter to get all the latest Laravel articles like this directly in your inbox.

Read more

© 2024 Extly, CB - All rights reserved.