MassAssignmentException in Laravel: Securing Your Models Against Silent Failures
Encountering a MassAssignmentException often signals a critical security oversight in your application's data flow. The error message explicitly identifies _token as the protected property causing the crash, which is a standard behavior for applications utilizing Laravel's CSRF protection. However, the root cause isn't just about that specific field; it stems from how the $fillable property (or its absence) interacts with mass assignment restrictions.
In your provided code, the Contacts model defines $table as an array containing database column names. This is a common mistake. The $table property should strictly hold the singular name of the table, not a list of columns. Defining it as ['name', 'mobile', ...] will cause Laravel to fail when resolving the table name for queries or migrations. While this specific syntax error might not be the direct trigger for the MassAssignmentException, fixing it is essential for the model to function correctly. The real culprit, however, lies in how you are handling data within the controller and the security defaults of Laravel 5.
When you call $contacts = Contacts::create($inputs), you are instructing Eloquent to insert every key-value pair from the request array into the database. In Laravel 5, if the protected $fillable property is not explicitly defined on the model, the default behavior changed significantly compared to earlier versions. Instead of allowing all mass assignment by default, Laravel now throws a MassAssignmentException if you attempt to fill properties that are not listed in $fillable.
The exception specifically mentions _token. This indicates that your form submission includes the CSRF token (e.g., via <meta name="_token" ...>), and your controller is passing the entire request payloadâincluding this hidden fieldâdirectly into the create method. Since _token is not defined in your $fillable array (which doesn't even exist yet), Laravel blocks the insertion to prevent potential token manipulation attacks or unintended data overwrites.
To resolve this, you must define the $fillable property on your Contacts model. This acts as an allowlist, ensuring that only specific attributes can be mass-assigned via methods like create, update, or toArray. Here is the corrected implementation for your model:
class Contacts extends Model
{
protected $table = 'contacts'; // Corrected to a singular string name
protected $fillable = [
'name',
'mobile',
'email',
'address'
// Note: created_at and updated_at are usually handled by the model itself
];
}
By restricting $fillable, you explicitly declare which fields are safe to populate from external inputs. This forces you to be intentional about data ingestion. If your form attempts to submit _token or remember_token, they will simply be ignored during the insert operation unless you specifically add them to the fillable array, which you generally should not do for security reasons.
Furthermore, your controller logic needs adjustment. While passing $request->all() is convenient in development, it bypasses Laravel's built-in validation and sanitization layers. A robust approach involves validating the request first and then using specific attributes rather than dumping the whole array:
public function store(Request $request)
{
// Validate only the intended fields
$validated = $request->validate([
'name' => 'required|string|max:255',
'mobile' => 'required|string',
'email' => 'required|email|unique:contacts,email',
'address' => 'nullable|string'
]);
// Pass only validated data to create
$contacts = Contacts::create($validated);
return redirect()->route('contacts.index');
}
This approach offers several advantages. First, it aligns with the principle of least privilege by limiting what data touches your database tables. Second, it ensures that CSRF tokens and other metadata are never accidentally persisted. Finally, it separates validation logic from data insertion, making your code more testable and secure against malformed inputs.
Remember that $table must be a string representing the singular table name, not an array of columns. If you need dynamic tables or aliases, handle that via the use statement in your migration or configuration, but keep the model definition clean.
For more details on securing Laravel applications and understanding mass assignment vulnerabilities, you can refer to resources like https://laravelcompany.com, which often covers security best practices and architectural patterns for modern PHP frameworks.