Table of Contents
Example 4
Output
Home Backend Development PHP Tutorial How to insert new user into MySQL table in Laravel?

How to insert new user into MySQL table in Laravel?

Sep 04, 2023 pm 02:25 PM
mysql laravel insert

How to insert new user into MySQL table in Laravel?

You can insert a new user as shown in the following example. To insert new users from Laravel you can use artisan seeder. To do this, first create a seeder−

using the following command
php artisan make:seeder UserSeeder
Copy after login

Once the command execution is completed, you will get the UserSeeder.php file in the database/seeders directory. Add the following code to the seed file to add user records to the users table.

The Chinese translation of

Example 1

is:

Example 1

<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class UserSeeder extends Seeder {
   /**
   * Run the database seeds.
   *
   * @return void
   */

   public function run(){
      foreach(range(1,1000) as $index) {
         DB::table('users')->insert([
            'name'=>Str::random(10),
            'email'=>Str::random(10).'@gmail.com',
            'password'=>Str::random(10)
         ]);
      }
   }
}
Copy after login

Now run the command to execute the seeder file−

php artisan db:seed --class=UserSeeder
Copy after login

Once you execute the command, you should be able to see the data in the users table.

The Chinese translation of

Example 2

is:

Example 2

Using the insert() method of the DB facade -

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class UserController extends Controller {
   public function index() {
      $user = DB::table('users')->insert([
         'name' => 'Vishal Khanna',
         'email' => 'vishal@email.com',
         'password' => 'vishal123',
      ]);
      if ($user) {
         echo "User inserted successfully!";
      } else {
         echo "Error while inserting user details";
      }
   }
}
Copy after login

DB facade insert() method is used to insert records into the user table.

Output

The output of the above code is −

User inserted successfully!
Copy after login
Copy after login
Copy after login

Example 3

Using create() method from Laravel eloquent model −

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;

class UserController extends Controller {
   public function index() {
      $user = User::create(['name'=>'Ashish Sehgal', 'email'=>'ashish@gmail.com', 'password'=>'ashish123']);
      if ($user) {
         echo "User inserted successfully!";
      } else {
         echo "Error while inserting user details";
      }
   }
}
Copy after login

Output

The output of the above code is −

User inserted successfully!
Copy after login
Copy after login
Copy after login
The Chinese translation of

Example 4

is:

Example 4

Use Laravel eloquent to insert data into the user table by creating a user object and using the save() method as shown below −

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;

class UserController extends Controller {
   public function index() {
      $user = new User();
      $user->name = 'Kiya Singh';
      $user->email ='kiya@gmail.com';
      $user->password='kiya123';
      $user->save();
      if ($user) {
         echo "User inserted successfully!";
      } else {
         echo "Error while inserting user details";
      }
   }
}
Copy after login

Output

The output of the above code is as follows −

User inserted successfully!
Copy after login
Copy after login
Copy after login

The above is the detailed content of How to insert new user into MySQL table in Laravel?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to start mysql by docker How to start mysql by docker Apr 15, 2025 pm 12:09 PM

The process of starting MySQL in Docker consists of the following steps: Pull the MySQL image to create and start the container, set the root user password, and map the port verification connection Create the database and the user grants all permissions to the database

MySQL's Role: Databases in Web Applications MySQL's Role: Databases in Web Applications Apr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

SQL and MySQL: Understanding the Relationship SQL and MySQL: Understanding the Relationship Apr 16, 2025 am 12:14 AM

The relationship between SQL and MySQL is the relationship between standard languages ​​and specific implementations. 1.SQL is a standard language used to manage and operate relational databases, allowing data addition, deletion, modification and query. 2.MySQL is a specific database management system that uses SQL as its operating language and provides efficient data storage and management.

MySQL: A Beginner-Friendly Approach to Data Storage MySQL: A Beginner-Friendly Approach to Data Storage Apr 17, 2025 am 12:21 AM

MySQL is suitable for beginners because it is easy to use and powerful. 1.MySQL is a relational database, and uses SQL for CRUD operations. 2. It is simple to install and requires the root user password to be configured. 3. Use INSERT, UPDATE, DELETE, and SELECT to perform data operations. 4. ORDERBY, WHERE and JOIN can be used for complex queries. 5. Debugging requires checking the syntax and use EXPLAIN to analyze the query. 6. Optimization suggestions include using indexes, choosing the right data type and good programming habits.

Solve database connection problem: a practical case of using minii/db library Solve database connection problem: a practical case of using minii/db library Apr 18, 2025 am 07:09 AM

I encountered a tricky problem when developing a small application: the need to quickly integrate a lightweight database operation library. After trying multiple libraries, I found that they either have too much functionality or are not very compatible. Eventually, I found minii/db, a simplified version based on Yii2 that solved my problem perfectly.

MySQL: Database Management System vs. Programming Language MySQL: Database Management System vs. Programming Language Apr 16, 2025 am 12:19 AM

MySQL is not only a database management system (DBMS) but also closely related to programming languages. 1) As a DBMS, MySQL is used to store, organize and retrieve data, and optimizing indexes can improve query performance. 2) Combining SQL with programming languages, embedded in Python, using ORM tools such as SQLAlchemy can simplify operations. 3) Performance optimization includes indexing, querying, caching, library and table division and transaction management.

How to solve SQL parsing problem? Use greenlion/php-sql-parser! How to solve SQL parsing problem? Use greenlion/php-sql-parser! Apr 17, 2025 pm 09:15 PM

When developing a project that requires parsing SQL statements, I encountered a tricky problem: how to efficiently parse MySQL's SQL statements and extract the key information. After trying many methods, I found that the greenlion/php-sql-parser library can perfectly solve my needs.

How to solve complex BelongsToThrough relationship problem in Laravel? Use Composer! How to solve complex BelongsToThrough relationship problem in Laravel? Use Composer! Apr 17, 2025 pm 09:54 PM

In Laravel development, dealing with complex model relationships has always been a challenge, especially when it comes to multi-level BelongsToThrough relationships. Recently, I encountered this problem in a project dealing with a multi-level model relationship, where traditional HasManyThrough relationships fail to meet the needs, resulting in data queries becoming complex and inefficient. After some exploration, I found the library staudenmeir/belongs-to-through, which easily installed and solved my troubles through Composer.

See all articles