What is protected $fillable in Laravel?
- 2
Hi,
Can anyone explain to me what does protected $fillable mean in Laravel?
Answers
- 1
In Laravel, $fillable is a property that you can define in an Eloquent model to specify which attributes are allowed to be mass-assigned using the create and update methods.
Mass assignment is a feature in some PHP frameworks, including Laravel, that allows you to set multiple attributes of a model at once using an array of data. This is often used when creating or updating models in a database.
Mass assignment can be a convenient way to set a large number of attributes at once, but it can also pose a security risk if not used properly. Without proper validation, a user could potentially submit a request with additional fields in the mass-assignment data that are not meant to be set, potentially leading to data manipulation or even data loss.
By default, when you create or update an Eloquent model, all of its attributes are mass-assigned. However, for security reasons, it is often desirable to limit the fields that can be mass-assigned. This is where $fillable comes in.
When you define $fillable on an Eloquent model, you are specifying an array of attributes that are allowed to be mass-assigned. For example, suppose you have a User model with name, email, and password attributes. You could define $fillable like this:
class User extends Model
{
protected $fillable = ['name', 'email', 'password'];
}
This means that when you create or update a User model, you can only mass-assign the name, email, and password attributes. Any other attributes will be ignored.
Note that if you want to block specific attributes from being mass-assigned, you should use $guarded property instead.
- 2
Imagine you have a form on a website where users can sign up. They fill in their name, email, and password. But, what if a sneaky user tries to add an extra field to the form, like "admin status," and sets it to "yes"? We don't want that!
Laravel uses $fillable to protect against this. It's like a security guard that only lets certain fields through. If a field isn't on the $fillable list, Laravel won't save it to the database.
Code Example:
Let's say you have a blog website, and you want users to create posts. A post has a title and content.
class Post {
protected $fillable = ['title', 'content'];
}
Here, only title and content are allowed. If someone tries to add another field, like "number of likes," Laravel won't save it because it's not on the $fillable list.
How to use it:
When someone creates a new post:
$post = Post::create([
'title' => 'My Awesome Post',
'content' => 'This is what I think...',
]);
Laravel checks the $fillable list and says, "Okay, title and content are allowed. I'll save them!"
In Simple Words:
$fillable is like a VIP list at a party. Only the names (or fields) on the list can get in. It helps keep our website safe from sneaky users trying to add things we don't want.