Laravel 5.4 field doesn't have a default value
Stefan Izdrail
Founder & Senior Architect · 2026-06-29
You are trying to create a new Match object using the Deal instance. This seems like a common scenario where one-to-many relationships exist between models. In this case, you have defined all needed relationships among your Deal, User, and Matches classes. However, you're facing an error when attempting to create a new Match.
The error message: QueryException in Connection.php line 647: SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into matches (deal_id) values (1))
In your case, you have defined your protected $guarded as an empty array:"The guarded property is an array holding all of the attributes that should be mass-assignable. By default, Eloquent will protect mass assignment for all fields unless explicitly defined in this array."
protected $guarded = [];
This means that Laravel doesn't protect any mass-assignment by default. In order to solve this issue, you need to properly fill the guarded array with the attributes that should be allowed for mass-assignment or provide explicit values for these columns.
To fix the problem in your exact use case (as mentioned in your example code), specify the 'user_id' field in the protected $guarded array:
protected $guarded = ['user_password', 'user_avatar'];
This ensures that only these two fields are mass-assignable and the rest of the attributes, including 'user_id', will not be assigned by default. You can also add explicit values for the required columns like 'user_id' in your creating or construct functions to avoid this error:
$deal->matches()->create(['user_id' => $userId]);
Or, assign values directly from within the constructor or boot function of your Match model class:
class Match extends Model{
// Other code...
public function __construct(User $user){
$this->user_id = $user->id;
// Set other attributes as per requirement.
}
}
These solutions should help you resolve your issue and improve the structure of your application, ensuring consistent data handling across all models involved in various relationships. Always remember to follow best practices while working with Eloquent relationships and mass-assignment. For more information on this topic, consult Laravel's documentation on Eloquent relationships and mass assignment at https://laravelcompany.com/blog/laravel-eloquent-relationships-mass-assignment.