Reputation: 1093
I get a very unhelpful error when I try and insert a new record in to my db. Does anyone have any idea where to start to solve this error?
user_id
That's all it says. (This is the name of one of my required fields in the table I'm saving to but it's not very descriptive.)
For reference here's my code:
$data = array(
'user_id'=>1,
'post_type'=>'0',
'post_title'=>'blah',
'description'=>'blah');
//it fails on this line
$id = Post::create($data);
Here's what my model looks like:
class Post extends Eloquent{
public static $rules = array(
'user_id'=>'required',
'post_type'=>'required',
'post_title' => 'required|max:25',
'description'=>'required'
);
public static function validate($data){
return Validator::make($data, static::$rules);
}
public function user(){
return $this->hasOne('User', 'id', 'user_id');
}
}
Tried getting rid of all relationships and validation in the model. That didn't work.
Upvotes: 1
Views: 7461
Reputation: 1519
This is called mass-assignment in Laravel, what you need to do to get it working on your model is to set a protected array called $guarded
to be empty. Add this to your model.
protected $guarded = array();
What this array does, it can prevent attributes to be mass-assigned with an array, if you don't want an attribute to be filled with the Model::create()
method, then you need to specify that attribute in the $guarded
array.
If instead you want to specify only the fillable attributes, Laravel's Eloquent also provides an array called $fillable
where you specify only the attributes that you want to fill via the mass-assigment way.
Further reading:
Mass Assignment: http://laravel.com/docs/eloquent#mass-assignment
Create Method: http://laravel.com/docs/eloquent#insert-update-delete
Upvotes: 4