Fill method in Laravel not working?
In your model you need to have protected $fillable = ['foo','bar']
;
Then you can do:
$event = new Event(array('foo' => "foo", "bar" => "bar"));
$event->save(); // Save to database and return back the event
dd($event);
The array key needs to be on the $fillable
, as Laravel will effectively call:
foreach ($array as $key => $value){
$event->$key = $value;
}
Alternatively, you can write directly to a column name:
$event = new Event();
$event->foo = "foo";
$event->bar = "bar";
$event->save();
dd($event);
Also make sure that the $fillable
property is defined in your model class. For example, in your new renamed model:
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['field1', 'field2'];
If you do not have either $fillable
or $guarded
defined on your Model, fill()
won't set any values. This is to prevent the model from mass assignment. See "Mass Assignment" on the Laravel Eloquent docs: http://laravel.com/docs/5.1/eloquent.
When filling the attributes, make sure to use an associative array:
$event->fill(array('field1' => 'val1', 'field2' => 'val2'));
A useful way to debug and check all your values:
//This will var_dump the variable's data and exit the function so no other code is executed
dd($event);
Hope this helps!
The attributes is a protected property. Use $obj->getAttributes() method.
Actually. at first you should change the model name from Event
to something else, Laravel
has a Facade
class as Illuminate\Support\Facades\Event
so it could be a problem.
Regarding the fill
method, you should pass an associative array to fill
method like:
$obj = new MyModel;
$obj->fill(array('fieldname1' => 'value', 'fieldname2' => 'value'));
Also make sure you have a protected $fillable
(check mass assignment) property declared in your Model
with property names that are allowed to be filled. You may also do the same thing when initializing the Model
:
$properties = array('fieldname1' => 'value', 'fieldname2' => 'value');
$obj = new ModelName($properties);
Finally, call:
// Instead of attributes
dd($obj->getAttributes());
Because attributes
is a protected property.
Use a key/value array in fill:
An example:
$book->fill(array(
'title' => 'A title',
'author' => 'An author'
));