Laravel Eloquent insert() Query Example: In this tutorial you will learn how to use insert() eloquent query in laravel application.
The laravel query builder provides us an insert method that may be used to insert records (data) into the database table. The insert method accepts an array of column names and values easily.
Example 1: Using Model
use App\Models\User;
class UserController extends Controller
{
public function index()
{
User::insert([
'email' => 'test@example.com',
'password' => Hash::make('12345678')
]);
}
}
Example 2: Using DB Query
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
class UserController extends Controller
{
public function index()
{
DB::table('users')->insert([
'email' => 'test@example.com',
'password' => Hash::make('12345678')
]);
}
}
Example 3:
You may insert several records at once by passing an array of arrays. Each array represents a record that should be inserted into the table:
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
class UserController extends Controller
{
public function index()
{
DB::table('users')->insert([
[
'name' => 'Test One',
'email' => 'test001@example.com',
'password' => Hash::make('12345678')
],
[
'name' => 'Test Two',
'email' => 'test002@example.com',
'password' => Hash::make('12345678')
]
]);
}
}
I hope its help you..