Laravel Inserting Data into Database
Inserting data in Laravel can be done using Eloquent ORM or the Query Builder. Eloquent provides a simple, object-oriented way to interact with your database, while the Query Builder offers a more manual approach for performing raw SQL-like queries. Here’s how you can insert data using both methods.
1. Inserting Data Using Eloquent
Laravel’s Eloquent ORM allows you to insert data into a table by creating a model instance and setting its attributes.
Example: Inserting a Single Record
To insert data using Eloquent, you first create a new instance of the model and then set the attributes. After that, you call the save()
method to insert the record into the database.
use App\Models\Post;
$post = new Post();
$post->title = 'My New Post';
$post->content = 'This is the content of the post';
$post->author_id = 1; // Assuming the table has an author_id field
$post->save();
This will insert a new record into the posts
table with the provided values for title
, content
, and author_id
.
Mass Assignment
You can insert data using mass assignment, which means passing an array of attributes to the model’s create()
method. For this to work, you must define which fields are fillable using the $fillable
property on the model.
use App\Models\Post;
class Post extends Model
{
protected $fillable = ['title', 'content', 'author_id'];
}
Now you can insert a record like this:
Post::create([
'title' => 'Another New Post',
'content' => 'Content of the post',
'author_id' => 1,
]);
This will automatically insert the values into the database.
Handling Mass Assignment Exception
If you don't set the $fillable
property or include a field that is not in the $fillable
array, Laravel will throw a MassAssignmentException
to prevent you from accidentally inserting unwanted or malicious data. To avoid this, always define $fillable
or $guarded
in your model.
2. Inserting Data Using Query Builder
The Query Builder provides a more SQL-like way of inserting data into the database. You can use the DB
facade to interact with the database directly.
Example: Inserting a Single Record
use Illuminate\Support\Facades\DB;
DB::table('posts')->insert([
'title' => 'My New Post',
'content' => 'This is the content of the post',
'author_id' => 1,
]);
This inserts a new record into the posts
table with the specified fields and values.
Inserting Multiple Records
You can insert multiple records at once by passing an array of arrays:
DB::table('posts')->insert([
['title' => 'First Post', 'content' => 'Content for first post', 'author_id' => 1],
['title' => 'Second Post', 'content' => 'Content for second post', 'author_id' => 2],
]);
This will insert two new rows into the posts
table.
3. Inserting and Getting the Inserted ID
If you need to retrieve the ID of the record you just inserted (often the primary key), you can use the insertGetId()
method with the Query Builder:
$id = DB::table('posts')->insertGetId([
'title' => 'Post with ID',
'content' => 'This is content for the post',
'author_id' => 1,
]);
echo $id; // Outputs the inserted ID
This is particularly useful when you need the ID for subsequent operations, such as creating related records.
4. Using save()
vs create()
save()
: You usesave()
when you manually instantiate the model and set its attributes.create()
: You usecreate()
for mass assignment when you pass an array of attributes. Remember that$fillable
or$guarded
must be set when usingcreate()
.
Example:
// Using save()
$post = new Post();
$post->title = 'Post Title';
$post->content = 'Post content';
$post->save();
// Using create()
Post::create([
'title' => 'Post Title',
'content' => 'Post content',
]);
Both methods will insert a new row into the database.
5. Timestamp Columns
By default, Eloquent automatically sets the created_at
and updated_at
columns when inserting data into a table (if those columns exist in your table). You don't need to explicitly set these values.
If you want to disable this behavior, you can set the $timestamps
property to false
in your model:
class Post extends Model
{
public $timestamps = false;
}
6. Handling JSON Data
Eloquent makes it easy to handle JSON data if you have a json
column in your table. You can set an attribute as an array or object, and Laravel will automatically convert it to JSON before inserting it into the database.
use App\Models\Post;
$post = new Post();
$post->title = 'Post with JSON data';
$post->meta = ['views' => 100, 'shares' => 10]; // Assuming 'meta' is a json column
$post->save();
This will insert the JSON representation of the meta
array into the meta
column.
7. Inserting Related Models (with Relationships)
If you are working with related models, you can easily insert related data. For example, if a Post
has many Comment
s, you can insert a comment for a specific post.
Example: Inserting Related Models
$post = Post::find(1);
$comment = new Comment();
$comment->content = 'This is a comment';
$post->comments()->save($comment);
This will insert a new comment and associate it with the post that has an id
of 1.
Alternatively, you can use the create()
method with relationships:
$post->comments()->create([
'content' => 'This is another comment',
]);
For this to work, you must ensure that the Comment
model has the $fillable
property defined.
8. Database Transactions
Sometimes you want to make sure that multiple inserts happen atomically (i.e., if one insert fails, none of them should persist). Laravel supports database transactions using the DB::transaction()
method.
Example: Using Transactions
use Illuminate\Support\Facades\DB;
DB::transaction(function () {
DB::table('posts')->insert([
'title' => 'Transactional Post',
'content' => 'Content of the post',
'author_id' => 1,
]);
DB::table('comments')->insert([
'post_id' => 1,
'content' => 'Comment on the post',
]);
});
If anything inside the transaction fails (e.g., a query throws an exception), the transaction will be rolled back, and no data will be inserted.
Summary
- Eloquent ORM allows you to insert data by creating model instances and using methods like
save()
orcreate()
. - Mass assignment lets you insert data by passing an array, but you must define
$fillable
attributes. - Query Builder offers a more manual way to insert data using
DB::table()
, with methods likeinsert()
andinsertGetId()
. - You can manage related models easily with Eloquent’s relationship methods.
- Timestamps are automatically handled by Eloquent unless disabled.
- JSON columns are seamlessly supported.
- Transactions ensure that inserts are atomic and can be rolled back in case of failure.
Eloquent simplifies the process of inserting data while providing powerful tools to handle various data types and relationships.