- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is Fillable Attribute in a Laravel model?
The fillable property is used inside the model. It takes care of defining which fields are to be considered when the user will insert or update data.
Only the fields marked as fillable are used in the mass assignment. This is done to avoid mass assignment data attacks when the user sends data from the HTTP request. So the data is matched with the fillable attributes before it is inserted into the table.
To understand fillable attributes let us create a model as shown below
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>
The model class for student is as follows −
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Student extends Model { use HasFactory; }
Let us add the fillable attribute with field names as shown below
<?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']; }
Let us use the create method in StudentController as shown below −
<?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' ]); } }
On executing the above code it will display the following on the browser.
{"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}
Inside the model it is mandatory to assign the field as either fillable or guarded. If not, following error will be generated –
Illuminate\Database\Eloquent\MassAssignmentException Add(name) to fillable property to allow mass assignment on [App\Models\Student]. http://127.0.0.1.8000/test