Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protect pivot table from mass assignment using eloquent

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?

like image 470
ivan.c Avatar asked Apr 17 '15 12:04

ivan.c


2 Answers

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.

like image 70
Margus Pala Avatar answered Nov 18 '22 07:11

Margus Pala


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

like image 26
Jay Dhameliya Avatar answered Nov 18 '22 07:11

Jay Dhameliya