What is protected $fillable in Laravel?

Question

Hi,

Can anyone explain to me what does protected $fillable  mean in Laravel?

Answer ( 1 )

    0
    2023-02-28T00:14:11+00:00

    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.

Leave an answer