I have following tables:
document: id, name;
author: id, name, job_title;
document_author: document_id, author_id, position
I'm passing an array of following structure:
$attributes = [name, job_title, position];
I'm trying to create author's model and attach it to document:
$author = \Author::create($attributes);
\Document::find($id)->authors()->save($author,$attributes);
Then I get QueryException
, because laravel tries to mass assign attributes to pivot table, while it should only pass a position
field.
The only solution I got is to filter array, like that:
$author = \Author::create($attributes);
$pivotAttributes = array_only($attributes, ['position'])
\Document::find($id)->authors()->save($author,$pivotAttributes);
Is there any better way, to define which columns of pivot table are fillable, better somewhere in the model or in it's relation?
I was digging in the Laravel code and I did not find any good way how to specify fillable nor guarded parameter to Pivot class even though it is subclass of Model.
This means that you approach is pretty good already.
Try it
$author = \Author::create($attributes);
$author->documents()->attach($id,["position"=>$request->get('position')]);
Show Doc http://laravel.com/docs/5.0/eloquent#inserting-related-models
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With