Laravel insert query | Laravel - Insert Records | Laravel database insert query | Laravel Eloquent insert() Query Example
In Laravel, you can insert records into a database table using both the Query Builder and Eloquent ORM. Below, I'll provide examples for both approaches:
Using Query Builder:
To insert records using the Query Builder, you can use the insert
method. Here's an example:
php
use Illuminate\Support\Facades\DB;
// Insert a single record
DB::table('your_table_name')->insert([
'column1' => 'value1',
'column2' => 'value2',
]);
// Insert multiple records as an array of associative arrays
$data = [
[
'column1' => 'value3',
'column2' => 'value4',
],
[
'column1' => 'value5',
'column2' => 'value6',
],
];
DB::table('your_table_name')->insert($data);
Replace 'your_table_name'
, 'column1'
, 'column2'
, 'value1'
, 'value2'
, etc., with your actual table name, column names, and values.
Using Eloquent ORM:
To insert records using Eloquent, you can create an instance of the corresponding model and set its attributes, then call the save
method. Here's an example:
Assuming you have a model named YourModel
associated with the table:
php
use App\Models\YourModel;
// Insert a single record
$record = new YourModel();
$record->column1 = 'value1';
$record->column2 = 'value2';
$record->save();
// Insert multiple records using a loop or array
$records = [
[
'column1' => 'value3',
'column2' => 'value4',
],
[
'column1' => 'value5',
'column2' => 'value6',
],
];
foreach ($records as $data) {
$record = new YourModel();
$record->fill($data);
$record->save();
}
Replace YourModel
, 'column1'
, 'column2'
, 'value1'
, 'value2'
, etc., with your actual model name, column names, and values.
In both examples, the data is inserted into the database table. The Query Builder approach is more suitable for raw database interactions, while the Eloquent approach is more commonly used when you have models defined for your tables, providing a more object-oriented way to work with your data.
Comments
Post a Comment