Black Friday: coupon FRIDAY24 for 40% off Yearly/Lifetime membership! Read more here

Eloquent updateOrCreate() and firstOrCreate(): 4 Real-World Examples

Laravel Eloquent has many features but it's hard to fully understand them without real-world examples. In this short tutorial, we will show real examples of two methods updateOrCreate() and firstOrCreate(), taken from open-source projects.


updateOrCreate() Example 1: System Settings

The first example comes from the open-source project Kovah/LinkAce.

class SystemSettingsController extends Controller
{
public function saveSystemSettings(SystemSettingsUpdateRequest $request): RedirectResponse
{
$settings = $request->except(['_token', 'guest_share']);
 
foreach ($settings as $key => $value) {
Setting::updateOrCreate([
'key' => $key,
'user_id' => null,
], [
'key' => $key,
'value' => $value,
'user_id' => null,
]);
}
}
}

In this example, we have a list of settings. Of course, the settings key should be unique, so updateOrCreate is used to check if key and user_id are equal to those provided.

If there is such a record, then it gets updated, otherwise it gets created.

Link to the source on GitHub: Kovah/LinkAce


updateOrCreate() Example 2: Company Address

The second example comes from the crater-invoice/crater open-source project.

class CompanyController extends Controller
{
public function updateCompany(CompanyRequest $request)
{
$company = Company::find($request->header('company'));
 
// ...
 
$company->address()->updateOrCreate(['company_id' => $company->id], $request->address);
 
return new CompanyResource($company);
}
}

In this example, every company needs to have only one address. So the updateOrCreate method checks if Address table contains an address for that company. If it does, then updates the current address, otherwise creates a new one.

Link to the source on GitHub: crater-invoice/crater


firstOrCreate() Example 1: User by GitHub ID

The first example for firstOrCreate() comes from spatie/spatie.be open-source repository.

class GitHubSocialiteController
{
protected function retrieveUser($gitHubUser): User
{
// ...
 
return User::firstOrCreate([
'github_id' => $gitHubUser->id,
], [
'password' => bcrypt(Str::random()),
'email' => $gitHubUser->email,
'name' => $gitHubUser->name ?? $gitHubUser->nickname,
]);
}
}

In this example, user registers or logs in using the GitHub OAuth provider. Of course, every time a user logs into the website, no need to create a new user in the DB. So, firstOrCreate() checks if the user exists, otherwise creates a new user.

Link to the source on GitHub: spatie/spatie.be


firstOrCreate() Example 2: Currency by Code

The second example for the firstOrCreate method comes from crater-invoice/crater.

class Version310 extends Listener
{
public function handle(UpdateFinished $event)
{
Currency::firstOrCreate(
[
'name' => 'Kyrgyzstani som',
'code' => 'KGS',
],
[
'name' => 'Kyrgyzstani som',
'code' => 'KGS',
'symbol' => 'С̲ ',
'precision' => '2',
'thousand_separator' => '.',
'decimal_separator' => ',',
]
);
 
// ...
}
}

In this example, firstOrCreate is used when a new version of the application is released.

In this new version, there were changes made for the Kyrgyzstani som currency. So using the firstOrCreate(), the application checks if this currency exists in the DB. If it does, it just updates the values for the record. Otherwise, it creates the record.

Link to the source on GitHub: crater-invoice/crater


These are just a few code examples of a few functions. You can find more open-source examples in the Code Example section of our website.

Also, if you want to learn more about Eloquent and its features, I have a 2-hour video course Eloquent: The Expert Level.

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 67 courses (1172 lessons, total 43 h 18 min)
  • 90 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent New Courses