How to Use create() Method in Laravel Eloquent
In Laravel Eloquent, use the
create() method to add a new record to the database by passing an array of attribute values. Make sure the model has $fillable or $guarded properties set to allow mass assignment before using create().Syntax
The create() method is called on an Eloquent model and accepts an array of key-value pairs representing the column names and their values. The model must allow mass assignment by defining $fillable or $guarded properties.
- Model::create(array $attributes): Creates and saves a new record with the given attributes.
php
Model::create([ 'column1' => 'value1', 'column2' => 'value2' ]);
Example
This example shows how to create a new user record using the create() method. The User model has $fillable set to allow mass assignment of name, email, and password.
php
<?php use App\Models\User; // In User model: // protected $fillable = ['name', 'email', 'password']; // Creating a new user record $user = User::create([ 'name' => 'Alice', 'email' => 'alice@example.com', 'password' => bcrypt('secret123') ]); // $user now contains the saved user instance
Output
User model instance saved with id, name='Alice', email='alice@example.com', and hashed password.
Common Pitfalls
Common mistakes when using create() include:
- Not setting
$fillableor$guardedin the model, causing aMassAssignmentException. - Passing attributes with keys that do not match database columns.
- Trying to use
create()without importing the model or using the correct namespace.
Always ensure mass assignment is configured and attribute keys are correct.
php
<?php // Wrong: No $fillable set in model // This will throw an error User::create(['name' => 'Bob']); // Right: Set $fillable in User model // protected $fillable = ['name']; User::create(['name' => 'Bob']);
Quick Reference
| Method | Description |
|---|---|
| create(array $attributes) | Creates and saves a new record with given attributes |
| $fillable | Array of attributes allowed for mass assignment |
| $guarded | Array of attributes not allowed for mass assignment |
| bcrypt(string $value) | Hashes a password before saving |
Key Takeaways
Use create() to quickly add new records by passing an array of attributes.
Always define $fillable or $guarded in your model to allow mass assignment.
Attribute keys in create() must match your database columns exactly.
create() returns the saved model instance with its database ID.
Use bcrypt() or similar to hash passwords before saving with create().