📜  laravel db inserr - PHP (1)

📅  最后修改于: 2023-12-03 15:02:34.792000             🧑  作者: Mango

Laravel DB Insert

Introduction

In Laravel, inserting data into a database can be done using the DB facade, which provides a set of methods for performing common database operations. In this article, we'll explore how to use the DB::insert method to insert data into a database table.

Prerequisites

Before we dive into the code, make sure you have the following installed:

  • Laravel v5.5 or higher
  • PHP v7.0 or higher
  • A database setup with the necessary credentials
Usage

To insert data into a database table, we first need to specify the table name and the data we want to insert. We can do this by passing an array of key-value pairs to the DB::insert method. The keys of the array should correspond to the column names of the table, and the values should be the data we want to insert.

$affected = DB::insert('insert into users (name, email) values (?, ?)', ['John Doe', 'johndoe@example.com']);

In the example above, we're inserting a new user with a name of 'John Doe' and an email address of 'johndoe@example.com'. The DB::insert method returns the number of rows that were affected by the insert statement.

We can also insert multiple rows at once by passing an array of arrays to the DB::insert method. Each nested array should contain the data for one row.

$data = [
    ['John Doe', 'johndoe@example.com'],
    ['Jane Doe', 'janedoe@example.com']
];
$affected = DB::insert('insert into users (name, email) values (?, ?)', $data);

In the example above, we're inserting two new users at once: 'John Doe' and 'Jane Doe'.

Conclusion

And there you have it! That's how you can use the DB::insert method in Laravel to insert data into a database table. Of course, there are many other methods available in the DB facade for performing other types of database operations. To learn more, check out the Laravel documentation.