您可以按照以下示例的方式插入新用户。要从Laravel插入新用户,可以使用artisan seeder。要做到这一点,首先使用以下命令创建一个seeder−
php artisan make:seeder UserSeeder
一旦命令执行完成,你将会在 database/seeders 目录下得到 UserSeeder.php 文件。将下面的代码添加到种子文件中,以向 users 表中添加用户记录。
<?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) ]); } } }
现在运行命令来执行seeder文件−
php artisan db:seed --class=UserSeeder
一旦执行该命令,您应该能够在用户表中看到其中的数据。
使用DB门面的insert()方法 -
<?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() 方法用于向用户表中插入记录。
上述代码的输出为−
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"; } } }
上述代码的输出为−
User inserted successfully!
使用Laravel eloquent通过创建用户对象并使用 save() 方法将数据插入到用户表中,如下所示−
<?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!
以上是在Laravel中如何向MySQL表中插入新用户?的详细内容。更多信息请关注PHP中文网其他相关文章!