vendredi 26 août 2016

Laravel 5 - proper way to update record with many-to-many association?

I'm new to Laravel, trying to figure out proper way of saving data with associations. I'm using version 5.3

For example: I have Publications that belongsToMany Authors

DD of request:

array:4 [▼
    "_token" => "something"
    "_method" => "PATCH"
    "name" => "Something"
    "authors" => array:2 [▼
        0 => "780"
        1 => "840"
    ]
]

First I've tried to do this:

public function update(Request $request, Publication $publication)
{
    $publication->update($request->all());
}

But got "unknown column authors" SQL error.

I've tried different approach:

public function update(Request $request, Publication $publication)
{
    $publication->update($request->except('authors'));
    $publication->authors()->sync($request->input('authors'));

    return redirect('/');
}

This time it works as expected. My question is: am I doing it right? Or there is a better / simpler way? May be possibility to do this update without explicit "slicing" or request? ($request->except('authors'))



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire