Reputation: 1052
I have the following Bus model:
class Bus extends Model
{
protected $guarded =[''];
protected $fillable = ['plate_num','seat_num'];
public function seats(){
return $this->hasMany(Seat::class);
}
public function addSeat($number){
$this->seats()->create([
'seat_num'=> $number
]);
}
}
And in my BusController I have the following store function that gets 2 values from a form('plate_num' and 'seats_num')
Although I have the $fillable array with the fields needed(Seat@seat_num and Bus@plate_num), however, Whenever I submit the form I get the following error:
MassAssignmentException in Model.php line 232 Seat_num
The logic of the code is basically whenever i key in the bus plate number and number of seats for example "ABC213" and "5", one record should be created in the buses table that includes the plate_num, and 5 records should b created in the Seats table whereby each record gets the id of the bus and the seat number.
Upvotes: 1
Views: 2413
Reputation: 1467
To fix Laravel MassAssignmentException in model.php need to follow below steps:
It can occur due to two possibilities:
For a mass assignment, need to provide all the fields of a model which will be mass assigned while during an update or create operation.
protected $fillable = ['age', 'phone', 'mail', 'location', 'created_at', 'updated_at'];
Table name should be assigned in $table = “user_info” in model file
Upvotes: 0
Reputation: 743
edit your model
protected $fillable = ['plate_num'];
add in your seat model
protected $fillable = ['seat_num'];
now you can use in your controller to add
use App\seat;
use App\bus;
public function add(){
$seat = new seat;
$bus = new bus;
Upvotes: 5
Reputation: 11906
Remove the following line in your model.
protected $guarded =[''];
You should only set guarded or fillable and not both. Also check if you've set the correct fillable properties in the related models. Posting more code of what you're trying to do will help.
Upvotes: 1
Reputation: 111829
You need to fill in $fillable
array in Seat
model and not in Bus
model.
When using:
$this->seats()->create(...);
you create Seat
models so in this case fillable is used from Seat
model.
Upvotes: 3