php - Laravel Eloquent create returning null id
370
I have an Eloquent modelFoo
, with a publicbar
array:
class Foo extends Model
{
public $bar = ['a', 'b', 'c'];
}
In thestore
method of my controller I want to access these variables, and create a newFoo
object:
public function store(Request $request)
{
$foo = new Foo;
foreach ($foo->bar as $field) {
$data[$field] = $request->{$field};
}
$foo->create($data);
return $foo->id;
}
The problem is that$foo->id
isnull
, although the object is created successfully.
Answer
Solution:
You can re-assign the
$foo
variable because thecreate
method will return the newly created instance.