Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is Fillable Attribute in a Laravel model?
The fillable attribute in Laravel models is a security feature that defines which database fields can be safely massassigned. It protects against mass assignment vulnerabilities by explicitly specifying which fields can be updated through methods like create() or update().
What is Mass Assignment?
Mass assignment occurs when you pass an array of data directly to model methods. Without proper protection, malicious users could potentially modify unintended fields by adding extra parameters to HTTP requests.
Setting Up Fillable Attributes
First, create a model using Artisan command ?
Run the following command to create a Student model:
php artisan make:model Student
Model created successfully.
Next, create a controller ?
Generate a controller with this command:
php artisan make:controller StudentController
Controller created successfully.
Example Implementation
Basic Model without Fillable
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Student extends Model {
use HasFactory;
}
Model with Fillable Attributes
<?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'];
}
Using Mass Assignment in Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Student;
class StudentController extends Controller {
public function index() {
$student = Student::create([
'name' => 'Rehan Khan',
'email' => 'rehan@gmail.com',
'address' => 'Xyz'
]);
return response()->json($student);
}
}
{"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}
Error Without Fillable
If you attempt mass assignment without defining fillable attributes, Laravel throws a MassAssignmentException ?
Illuminate\Database\Eloquent\MassAssignmentException Add [name] to fillable property to allow mass assignment on [App\Models\Student].
Alternative: Guarded Attribute
Instead of $fillable, you can use $guarded to specify fields that should NOT be massassigned ?
// Allow all fields except 'id' and 'created_at' protected $guarded = ['id', 'created_at'];
Conclusion
The fillable attribute is essential for secure Laravel applications. It prevents unauthorized field modifications while enabling convenient mass assignment for legitimate operations. Always define either $fillable or $guarded in your models.
