您可以按照以下範例的方式插入新使用者。若要從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中文網其他相關文章!