I have inherited a project that has a a few CRUD forms ... On the create form we need to create entries for a hasMany
and belongsToMany
relationship. So basically what i have got is the following
$movie = Movie::create($request->validated());
// Then to save the belongsToMany
foreach ($request['actors'] as $actor) {
// do some data manipulation
$actor = Actor::where('code', $actor->code)->first();
$movie->actors()->attach($actor);
}
// Save the hasMany
foreach ($request['comments'] as $comment) {
// do some data manipulation
$movie->comments()->create([
'title' => $comment['title'],
'body' => $comment['body'],
]);
}
I'm not sure if this is the best way of doing this, but it seems to work.
The problem I am having is that in the edit
form, these actors / comments can be edited, added to or deleted and i am unsure of how to go about updating them. Is it possible to update them, or would it be better to delete the existing relationship data and re-add them?
I have never updated relationships, only added them so i am unsure how to even start.
Any help would be greatly appreciated.
CodePudding user response:
As laravel doc suggested you can use saveMany()
method for storing relationship instances.
// Save the hasMany
foreach ($request['comments'] as $comment) {
$comments[] = [
new Comment([
'title' => $comment['title'],
'body' => $comment['body'],
]);
];
}
!empty($comments) && $movie->comments()->saveMany($comments);
For deletion and update you should define two routes, one for updating comment and one for deleting comment.
Route::patch('movie/{movie}/comment/{comment}',[MovieController::class,'updateComment']);
Route::delete('movie/{movie}/comment/{comment}',[MovieController::class,'deleteComment']);