PHP
Atomically Retrieve or Create/Update Eloquent Records
Learn to use `firstOrCreate` and `updateOrCreate` to elegantly retrieve an Eloquent model by attributes or create/update it if it doesn't exist, ensuring data integrity.
use App\Models\User;
use App\Models\Post;
// --- firstOrCreate ---
// Try to find a user by email.
// If not found, create a new user with the given email and additional attributes.
$user = User::firstOrCreate(
['email' => '[email protected]'],
['name' => 'John Doe', 'password' => bcrypt('secret')] // Attributes for creation
);
echo "User ID: " . $user->id . "
";
// --- updateOrCreate ---
// Try to find a post by title and author_id.
// If found, update its content and published status.
// If not found, create a new post with all provided attributes.
$post = Post::updateOrCreate(
['title' => 'My First Post', 'user_id' => $user->id],
['content' => 'This is the amazing content.', 'published_at' => now()] // Attributes for creation or update
);
echo "Post ID: " . $post->id . "
";
How it works: The `firstOrCreate` and `updateOrCreate` methods provide a convenient and atomic way to manage records in your database. `firstOrCreate` attempts to find a record matching the first array of attributes. If found, it returns the model instance. If not, it creates a new record with both the first array of attributes and the second array (default values). `updateOrCreate` works similarly, but if a matching record is found, it updates that record with the attributes from the second array, otherwise it creates a new one using all attributes provided. These methods are essential for 'upsert' operations.