Fixed - Model MassAssignmentException in Laravel
In Laravel, a MassAssignmentException is thrown when you attempt to mass-assign values to a model that are not supposed to be assigned. This is a security feature that helps protect against unauthorized changes to the database.
By default, Laravel only allows mass assignment of attributes that are explicitly defined in the model's $fillable or $guarded arrays. If you attempt to assign a value to an attribute that is not included in either of these arrays, you will get a MassAssignmentException.
For example, consider the following model:
app/Models/User.php
class User extends Model
{
protected $fillable = ['name', 'email', 'password'];
}
In this case, only the "name", "email", and "password" attributes can be mass-assigned. If you attempt to mass-assign any other attributes, you will get a MassAssignmentException.
To resolve this issue, you can either add the attribute to the $fillable array, or you can use the $guarded array to specify attributes that should not be mass-assigned:
app/Models/User.php
class User extends Model
{
protected $guarded = ['id', 'created_at', 'updated_at'];
}
In this case, the "id", "created_at", and "updated_at" attributes are protected from mass-assignment.
In addition to the $fillable and $guarded arrays, you can also define a custom fillable method on the model to allow mass-assignment of specific attributes based on certain conditions.
Overall, MassAssignmentException is a useful security feature in Laravel that helps prevent unauthorized changes to the database, but it can be easily resolved by properly defining the fillable or guarded attributes on your models.
I hope it can help you...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- How to Add Custom Attribute in Laravel Model?
- Get Array of Ids from Eloquent Models in Laravel
- How to Set Default Value in Laravel Model?
- How to Get All Models in Laravel?
- How to Get Columns Names from Model in Laravel?
- How to Create Model in Laravel using Command?
- Laravel Eloquent Model Custom Function Example
- How to Create Custom Model Events in Laravel?
- Laravel Replicate Model with Relationships Example
- Laravel Improve Speed Performance using Model Caching Tutorial
- Laravel Model Disable created_at and updated_at Update Record
- How to disable model timestamps in Laravel?
- How to Get Table Name from Model in Laravel?