PHP

Create or Update Eloquent Records with `updateOrCreate`

Discover Laravel's `updateOrCreate` method for Eloquent models, allowing you to elegantly insert a new record or update an existing one based on specified attributes.

<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function storeOrUpdate(Request $request)
    {
        // Define attributes to search by (unique identifier)
        $matchingAttributes = [
            'email' => $request->input('email'),
        ];

        // Define attributes to update or create with
        $otherAttributes = [
            'name' => $request->input('name', 'Default Name'),
            'password' => bcrypt($request->input('password', 'secret')),
        ];

        // Attempt to find a user by email. If found, update. If not, create a new user.
        $user = User::updateOrCreate(
            $matchingAttributes,
            $otherAttributes
        );

        if ($user->wasRecentlyCreated) {
            return response()->json(['message' => 'User created successfully', 'user' => $user], 201);
        } else {
            return response()->json(['message' => 'User updated successfully', 'user' => $user], 200);
        }
    }
}
How it works: The `updateOrCreate` method is a powerful Eloquent feature that simplifies 'upsert' operations. It attempts to locate a record using the first array of attributes (`$matchingAttributes`). If a matching record is found, it updates that record with the attributes provided in the second array (`$otherAttributes`). If no record is found, a new one is created using a combination of both attribute arrays. This ensures idempotency and reduces boilerplate code for common create/update scenarios.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs