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 commandphp artisan make:seeder UserSeeder
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<?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) ]); } } }
Now run the command to execute the seeder file−
php artisan db:seed --class=UserSeeder
Once you execute the command, you should be able to see the data in the users table.
The Chinese translation ofUsing 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"; } } }
DB facade insert() method is used to insert records into the user table.
The output of the above code is −
User inserted successfully!
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"; } } }
The output of the above code is −
User inserted successfully!
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"; } } }
The output of the above code is as follows −
User inserted successfully!
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!