Laravel 模型中的 Fillable 属性是什么?

laravelphpserver side programming更新于 2025/10/7 14:22:17

fillable 属性在模型内部使用。它负责定义用户插入或更新数据时需要考虑的字段。

只有标记为 fillable 的字段才会用于批量赋值。这样做是为了避免用户通过 HTTP 请求发送数据时遭受批量赋值数据攻击。因此,数据在插入到表中之前会与 fillable 属性进行匹配。

为了理解 fillable 属性,我们创建一个如下所示的模型

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

C:\xampp\htdocs\laraveltest>

Now let us create a studentController using command −

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中的创建方法,如下所示 -

<?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

相关文章