Laravel 模型中的可填充屬性是什麼?


可填充屬性在模型內部使用。它負責定義使用者在插入或更新資料時需要考慮哪些欄位。

只有標記為可填充的欄位在批次分配中使用。這樣做是為了避免在使用者從 HTTP 請求傳送資料時發生批次分配資料攻擊。因此,在將資料插入表中之前,會將其與可填充屬性進行匹配。

為了理解可填充屬性,讓我們建立一個模型,如下所示

php artisan make:model Student
C:\xampp\htdocs\laraveltest>php artisan make:model Student
Model created successfully.

C:\xampp\htdocs\laraveltest>

現在讓我們使用命令建立 StudentController

php artisan make:controller StudentController
C:\xampp\htdocs\laraveltest>php artisan make:controller StudentController
Controller created successfully.

C:\xampp\htdocs\laraveltest>

該學生的模型類如下所示 −

<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Student extends Model { use HasFactory; }

讓我們新增具有如下所示欄位名的可填充屬性

<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Student extends Model { use HasFactory; protected $fillable = ['name','email','address']; }

讓我們在 StudentController 中使用 create 方法,如下所示 −

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Student; class StudentController extends Controller { public function index() { echo $student = Student::create([ 'name' => 'Rehan Khan', 'email'=>'rehan@gmail.com', 'address'=>'Xyz' ]); } }

執行以上程式碼,它將在瀏覽器上顯示以下內容。

{"name":"Rehan Khan","email":"rehan@gmail.com","address":"Xyz","updated_at":"2022-05-01T13:49:50.000000Z","created_at":"2022-05-01T13:49:50.000000Z","id":2}

在模型內,必須將欄位分配為可填充或受保護。否則,將生成以下錯誤 –

Illuminate\Database\Eloquent\MassAssignmentException
Add(name) to fillable property to allow mass assignment on [App\Models\Student].
http://127.0.0.1.8000/test

更新於: 2022 年 8 月 29 日

27K+ 瀏覽量

開啟您的 職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.