Laravel Eloquent makes working with databases easy, safe, and efficient. Its create() family helps you insert, update, or prevent duplicate records with minimal code. Here’s a quick guide.
create() – Simple Insert
- Inserts a new record using mass assignment.
- Requires $fillable or $guarded in the model.
- Throws an error if a record already exists.
User::create([
'name' => 'John Doe',
'email' => '[email protected]',
'password' => bcrypt('secret')
]);
firstOrCreate() – Insert If Missing
- Searches for a record first.
- Creates a new record only if it doesn’t exist.
- Returns a saved model.
User::firstOrCreate(
['email' => '[email protected]'],
['name' => 'AA', 'password' => bcrypt('pass')]
);
firstOrNew() – Prepare Without Saving
- Similar to firstOrCreate(), but doesn’t save if not found.
- Returns an unsaved model instance for further modifications.
$user = User::firstOrNew(['email' => '[email protected]'], ['name' => 'AA']);
$user->password = bcrypt('secret');
$user->save();
updateOrCreate() – Upsert (Update or Insert)
- Finds a record and updates if it exists.
- Creates a new record if not found.
User::updateOrCreate(
['email' => '[email protected]'],
['name' => 'Updated Name', 'status' => 'active']
);
Tips
- Always protect mass assignment with
$fillable. - Use
firstOrCreate()to avoid duplicates in seeders. - Use
updateOrCreate()for upserts. - Use
firstOrNew()when you need extra control before saving.
Master these methods to write cleaner, safer, and more efficient database code!