如何在Laravel中将新用户插入MySQL表?
您可以通过以下几种方式插入新用户,如下例所示。要从Laravel插入新用户,您可以使用artisan seeder。为此,首先使用以下命令创建一个seeder:
php artisan make:seeder UserSeeder
命令执行后,您将在database/seeders目录下得到**UserSeeder.php**文件。将代码添加到seeder文件中,以在users表中添加用户记录,如下所示。
示例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) ]); } } }
现在运行命令来执行seeder文件:
php artisan db:seed --class=UserSeeder
命令执行后,您应该能够在users表中看到数据。
示例2
使用DB facade的**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' => '[email protected]', 'password' => 'vishal123', ]); if ($user) { echo "User inserted successfully!"; } else { echo "Error while inserting user details"; } } }
DB facade的**insert()**方法用于将记录插入users表。
输出
上述代码的输出为:
User inserted successfully!
示例3
使用Laravel eloquent模型的**create()**方法:
<?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'=>'[email protected]', 'password'=>'ashish123']); if ($user) { echo "User inserted successfully!"; } else { echo "Error while inserting user details"; } } }
输出
上述代码的输出为:
User inserted successfully!
示例4
使用Laravel eloquent通过创建用户对象并使用**save()**方法插入users表,如下所示:
<?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 ='[email protected]'; $user->password='kiya123'; $user->save(); if ($user) { echo "User inserted successfully!"; } else { echo "Error while inserting user details"; } } }
输出
上述代码的输出如下:
User inserted successfully!
广告