简体   繁体   中英

MassAssignmentException in Model.php line 232

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.

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;

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM