DEV Community

Shariful Ehasan
Shariful Ehasan

Posted on

Laravel Eloquent’s create() Methods

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' => 'john@example.com',
    'password' => bcrypt('secret')
]);
Enter fullscreen mode Exit fullscreen mode

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' => 'a@a.com'],
    ['name' => 'AA', 'password' => bcrypt('pass')]
);
Enter fullscreen mode Exit fullscreen mode

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' => 'a@a.com'], ['name' => 'AA']);
$user->password = bcrypt('secret');
$user->save();
Enter fullscreen mode Exit fullscreen mode

updateOrCreate() – Upsert (Update or Insert)

  • Finds a record and updates if it exists.
  • Creates a new record if not found.
User::updateOrCreate(
    ['email' => 'a@a.com'],
    ['name' => 'Updated Name', 'status' => 'active']
);
Enter fullscreen mode Exit fullscreen mode

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!

Top comments (1)

Collapse
 
xwero profile image
david duymelinck

While it is good to know those methods exist. The problem with the methods is that the database layer has too much control over the application behavior.

Create actions, certainly user creation, often trigger side actions like sending a welcome mail. By using firstOrCreate or updateOrCreate the application doesn't know which action is executed. So it is harder for the application to trigger the appropriate actions.

firstOrNew is the best of the functions. But instead of checking if the model is new or not, returning a not found message is the most clear way for the application to know what to do.

In short while the methods can be convenient, they make it harder to write code that is easy to maintain.