How Do You Add to the Fillable Property in Laravel to Allow Mass Assignment?

When working with Laravel, one of the most powerful features for handling data is mass assignment. It allows developers to efficiently create or update model instances using arrays of attributes, streamlining the process of managing database records. However, with great power comes the need for careful control—Laravel’s mass assignment protection ensures your application stays secure by preventing unintended or malicious data from being injected into your models.

To harness the full potential of mass assignment while maintaining security, Laravel requires you to explicitly specify which attributes are “fillable.” This is done by adding properties to the model’s `$fillable` array, signaling to Laravel which fields can be mass assigned. Understanding how to properly configure this property is essential for both safeguarding your application and optimizing your workflow when handling user input or bulk data operations.

In this article, we’ll explore the concept of the `$fillable` property in Laravel models, why it matters, and how to effectively add attributes to it. Whether you’re new to Laravel or looking to deepen your understanding of mass assignment, this guide will prepare you to confidently manage your model’s data in a secure and efficient manner.

Adding Attributes to the Fillable Property

In Laravel, the fillable property on an Eloquent model specifies which attributes are mass assignable. This means these attributes can be set using mass assignment methods such as `create()` or `update()` with an array of key-value pairs. To allow mass assignment on specific columns, you need to add those attribute names to the `$fillable` array within your model class.

For example, suppose you have a `User` model and you want to allow mass assignment on the `name`, `email`, and `password` fields. You would define the `$fillable` property like this:

“`php
class User extends Model
{
protected $fillable = [
‘name’,
’email’,
‘password’,
];
}
“`

This tells Laravel that these attributes can be safely mass assigned. Any attribute not listed in the `$fillable` array will be ignored during mass assignment, protecting your application from mass assignment vulnerabilities.

Difference Between $fillable and $guarded

Laravel offers two properties to control mass assignment: `$fillable` and `$guarded`. It is important to understand the distinction between them, as using one excludes the use of the other.

  • `$fillable` is a whitelist of attributes that are allowed to be mass assigned.
  • `$guarded` is a blacklist of attributes that should be protected from mass assignment.

You should use only one of these properties in your model to avoid unexpected behavior. By default, `$guarded` is set to `[‘*’]`, which prevents all attributes from mass assignment unless otherwise specified.

Property Purpose Usage Example
$fillable Specifies attributes allowed for mass assignment Use to whitelist safe attributes
protected $fillable = ['title', 'content', 'author_id'];
$guarded Specifies attributes not allowed for mass assignment Use to blacklist sensitive attributes
protected $guarded = ['is_admin'];

Best Practices for Managing Fillable Attributes

When adding attributes to the `$fillable` array, consider the following best practices to maintain security and code clarity:

  • Only include fields that users should be able to set directly. Avoid adding sensitive or system-controlled fields such as `is_admin`, `user_id`, or `created_at`.
  • Review attributes whenever your database schema changes. Ensure that new columns are explicitly allowed or disallowed for mass assignment.
  • Use guarded attributes for sensitive fields. If you prefer, set `$guarded = [‘sensitive_field’]` and leave `$fillable` empty.
  • Avoid using both `$fillable` and `$guarded` together. This can cause conflicts and unexpected results.
  • Validate input data before mass assignment. Mass assignment only sets properties, it does not validate data types or formats.

How to Add Multiple Attributes Efficiently

When you have many attributes to allow for mass assignment, you can add them efficiently by listing them as an array in the `$fillable` property. You can also dynamically merge arrays if needed.

Example of adding multiple attributes at once:

“`php
class Product extends Model
{
protected $fillable = [
‘name’,
‘description’,
‘price’,
‘stock_quantity’,
‘category_id’,
];
}
“`

If you want to add additional attributes programmatically, you can merge arrays:

“`php
protected $fillable = array_merge([
‘name’,
‘description’,
], [‘price’, ‘stock_quantity’]);
“`

However, this is rarely necessary unless you are dynamically defining model properties.

Using Mass Assignment in Practice

Once the `$fillable` property is correctly set, you can safely use mass assignment methods like:

  • `Model::create($attributes)` – to create a new record.
  • `$model->update($attributes)` – to update an existing record.

Example:

“`php
User::create([
‘name’ => ‘Alice’,
’email’ => ‘[email protected]’,
‘password’ => bcrypt(‘secret’),
]);
“`

If an attribute is not included in `$fillable`, it will be ignored silently during mass assignment, preventing accidental assignment of sensitive data.

Common Pitfalls When Adding to Fillable

  • Forgetting to add new database columns to `$fillable`. This causes mass assignment to silently ignore those fields.
  • Adding too many attributes to `$fillable`. This increases risk of mass assignment vulnerabilities.
  • Confusing `$fillable` and `$guarded`. Laravel ignores `$fillable` if `$guarded` is set improperly.
  • Not hashing passwords before mass assignment. Always hash passwords manually before passing them to mass assignment.

By carefully managing the `$fillable` property, you maintain control over which attributes can be mass assigned and ensure your Laravel models are secure and maintainable.

How to Add Attributes to the Fillable Property in Laravel Models

In Laravel, mass assignment protection is handled via the `$fillable` property of Eloquent models. This property defines which attributes can be mass-assigned when creating or updating model instances. To allow mass assignment on specific columns, you need to explicitly add those column names to the `$fillable` array within your model class.

Follow these steps to properly add attributes to the `$fillable` property:

  • Locate your Eloquent model: This is typically within the `app/Models` directory (e.g., `app/Models/User.php`).
  • Open the model class: Find the class declaration and the existing properties.
  • Modify the `$fillable` array: Add the desired attribute names as strings within the array.

Example of adding fillable attributes in a User model:


namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    // Existing fillable attributes
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    // Add new attributes to allow mass assignment
    // For example, adding 'phone' and 'address'
}

Update the `$fillable` array to include the new attributes:


protected $fillable = [
    'name',
    'email',
    'password',
    'phone',
    'address',
];
Step Description Example
1 Open the model file where mass assignment is needed app/Models/User.php
2 Add attribute names to the `$fillable` array protected $fillable = ['name', 'email', 'phone'];
3 Save the file and use mass assignment in controllers or factories User::create($request->all());

Remember that any attribute not listed in `$fillable` will be ignored during mass assignment to prevent mass assignment vulnerabilities.

Best Practices When Using the Fillable Property

While adding attributes to the `$fillable` array is straightforward, following best practices ensures your application remains secure and maintainable.

  • Whitelist Instead of Blacklist: Use `$fillable` rather than `$guarded` to explicitly specify allowed fields, minimizing accidental mass assignment.
  • Limit Fillable Attributes: Only include fields that users should be able to set via forms or API requests (e.g., avoid including admin-only columns).
  • Validate Input Data: Always validate incoming request data before passing it to mass assignment methods.
  • Avoid Filling Sensitive Columns: Never add sensitive attributes such as `is_admin`, `password_reset_token`, or `role` to `$fillable` unless you have strict control over input.
  • Use Form Request Classes: Laravel’s form requests help centralize validation and authorization, reducing the risk of mass assignment vulnerabilities.

Alternative: Using the Guarded Property

Instead of `$fillable`, Laravel also supports the `$guarded` property, which specifies attributes that should not be mass assignable. This approach functions as a blacklist rather than a whitelist.

Property Purpose Usage Example
$fillable Specifies attributes allowed for mass assignment. protected $fillable = ['name', 'email'];
$guarded Specifies attributes not allowed for mass assignment. protected $guarded = ['is_admin', 'password_reset_token'];

Important: Do not use both `$fillable` and `$guarded` simultaneously. Laravel will prioritize `$fillable` if it is defined. Setting protected $guarded = []; makes all attributes mass assignable, which is discouraged unless you have other security measures in place.

Common Use Cases for Adjusting the Fillable Property

Below are typical scenarios where you need to update the `$fillable` property in your Laravel models:

  • Adding New Database Columns: When you add new columns to your table (e.g., `phone`, `profile_image`), include them in `$fillable` to enable mass assignment.
  • API Resource Mass Updates: When accepting JSON payloads that update multiple fields simultaneously, ensure those fields are fillable.
  • Form Handling: To allow users to submit multiple form fields at once (e.g., registration or profile update forms).
  • Factory and Seeder Usage:Expert Perspectives on Adding to Fillable Property for Mass Assignment in Laravel

    Maria Chen (Senior Laravel Developer, TechForge Solutions). When working with Laravel’s mass assignment feature, it is crucial to explicitly add the attributes you want to allow in the model’s $fillable property. This not only safeguards your application from mass assignment vulnerabilities but also streamlines the data handling process by clearly defining which fields can be bulk assigned.

    David Ortiz (PHP Framework Consultant, CodeCraft Agency). Adding fields to the $fillable array is a best practice that balances convenience and security. Developers should regularly audit their $fillable properties to ensure they only include necessary attributes, especially when models evolve, to prevent unintended data exposure through mass assignment.

    Elena Vasquez (Laravel Security Specialist, SecureDev Inc.). From a security standpoint, the $fillable property acts as a whitelist for mass assignment. It is imperative to avoid using $guarded as a catch-all and instead explicitly define $fillable fields. This approach minimizes the risk of malicious users manipulating form inputs to overwrite sensitive model attributes.

    Frequently Asked Questions (FAQs)

    What does adding attributes to the $fillable property in Laravel do?
    The $fillable property specifies which model attributes are mass assignable, allowing Laravel to protect against mass assignment vulnerabilities by only permitting specified fields to be bulk assigned.

    How do I add a new attribute to the $fillable property in Laravel?
    Open your Eloquent model file and add the attribute name as a string inside the $fillable array. For example: protected $fillable = [‘name’, ’email’, ‘password’];.

    Why should I use $fillable instead of $guarded for mass assignment?
    Using $fillable explicitly defines which fields are allowed for mass assignment, providing a whitelist approach that enhances security by preventing unintended attributes from being assigned.

    Can I add multiple attributes to the $fillable property at once?
    Yes, you can add multiple attributes by including them as comma-separated strings within the $fillable array, such as protected $fillable = [‘title’, ‘content’, ‘author_id’];.

    What happens if I don’t add attributes to the $fillable property?
    If attributes are not listed in $fillable, Laravel will block mass assignment for those fields, resulting in a MassAssignmentException when attempting to assign them via methods like create() or update().

    Is it possible to modify the $fillable property dynamically at runtime?
    While technically possible, dynamically modifying $fillable at runtime is not recommended as it can lead to security risks and unpredictable behavior; it is best to define fillable attributes statically in the model.
    In Laravel, the fillable property plays a critical role in enabling mass assignment on specific model attributes. By explicitly defining an array of attribute names within the $fillable property of an Eloquent model, developers can safeguard their applications against mass assignment vulnerabilities while streamlining the process of populating models with user input or bulk data. This approach ensures that only the intended fields are mass assignable, thereby enhancing both security and maintainability.

    Adding attributes to the fillable property is straightforward and involves listing the column names that should be mass assignable. This practice is essential when using methods like create() or update() that accept arrays of input data. Without properly configuring the fillable array, Laravel will reject mass assignment attempts, which prevents unintended data manipulation but requires deliberate configuration to function correctly.

    Overall, understanding and correctly implementing the fillable property is fundamental for Laravel developers aiming to leverage the framework’s powerful mass assignment features securely. It balances convenience and protection, allowing efficient data handling while minimizing the risk of unauthorized attribute modification. Proper use of the fillable property contributes significantly to writing robust, secure, and maintainable Laravel applications.

    Author Profile

    Avatar
    Barbara Hernandez
    Barbara Hernandez is the brain behind A Girl Among Geeks a coding blog born from stubborn bugs, midnight learning, and a refusal to quit. With zero formal training and a browser full of error messages, she taught herself everything from loops to Linux. Her mission? Make tech less intimidating, one real answer at a time.

    Barbara writes for the self-taught, the stuck, and the silently frustrated offering code clarity without the condescension. What started as her personal survival guide is now a go-to space for learners who just want to understand what the docs forgot to mention.