Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5: when persist form data, _token causes mass assignment exception

When I try to persist form data, Laravel is throwing a mass assignment exception.

In the view I'm using {!! form::open(...) !!} which I know creates _token as a hidden field.

When the form data is sent to the controller, I'm using

$data = Input::all();
$order = Order::create($data);
$order->save();

Should I be adding a field for _token in my database? Or am I causing an error by doing something else wrong?

like image 952
Brent Connor Avatar asked Apr 08 '15 13:04

Brent Connor


People also ask

What does mass assignable mean in laravel?

Mass assignment is when you send an array to the model creation, basically setting a bunch of fields on the model in a single go, rather than one by one, something like: $user = new User(request()->all()); (This is instead of explicitly setting each value on the model separately.)

What is the difference between fillable and guarded in laravel?

The guarded attribute is the opposite of fillable attributes. In Laravel, fillable attributes are used to specify those fields which are to be mass assigned. Guarded attributes are used to specify those fields which are not mass assignable.

What is protected $fillable in laravel?

The fillable property is used inside the model. It takes care of defining which fields are to be considered when the user will insert or update data. Only the fields marked as fillable are used in the mass assignment. This is done to avoid mass assignment data attacks when the user sends data from the HTTP request.


2 Answers

A mass assignment exception is usually caused because you didn't specify the fillable (or guarded the opposite) attributes in your model. Do this:

class Order extends Eloquent {
    protected $fillable = ['field1', 'foo', 'bar'];
}

This way you also don't have to worry about _token because only the specified fields will be filled and saved in the db no matter what other stuff you pass to the model.

like image 69
lukasgeiter Avatar answered Sep 30 '22 03:09

lukasgeiter


or

protected $guarded = array();
like image 26
Yash Avatar answered Sep 30 '22 03:09

Yash