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'=>'[email protected]', 'address'=>'Xyz' ]); } }
执行以上代码,它将在浏览器上显示以下内容。
{"name":"Rehan Khan","email":"[email protected]","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
广告