Protect pivot table from mass assignment using eloquent

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • lauren89
    New Member
    • Apr 2015
    • 1

    #1

    Protect pivot table from mass assignment using eloquent

    Hi

    I have following tables:

    Code:
    document: id, name;
    author: id, name, job_title;
    document_author: document_id, author_id, position
    I'm passing an array of following structure:

    Code:
    $attributes = [name, job_title, position]; 
    
    I'm trying to create author's model and attach it to document:
    Code:
    $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 I got is to filter array, like that:

    Code:
    $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?
Working...