This is a controller, which receives the validated input from a http request, then finds the assorted model and for each translation key in the received data, it will add it to the model.
public function update(UpdateMenuItemRequest $request)
{
$validated = $request->validated();
$item = MenuItem::findOrFail($validated['id']);
foreach($validated['translations'] as $validatedTranslation) {
$item->translations()->updateOrCreate(['locale' => $validatedTranslation['locale']], $validatedTranslation);
}
return $item;
}
Is this Object Oriented enough? It doesn't seem like this method is violating SRP in the first place, or could it be improved? Thank you.
1 Answer 1
You could use route model binding to remove some lines from your code, but that would require changing the route so it passes the MenuItem's id.
(削除) public function update(UpdateMenuItemRequest $request) (削除ここまで)
public function update(MenuItem $item, UpdateMenuItemRequest $request)
{
$validated = $request->validated();
(削除) $item = MenuItem::findOrFail($validated['id']); (削除ここまで)
foreach($validated['translations'] as $validatedTranslation) {
$item->translations()->updateOrCreate(['locale' => $validatedTranslation['locale']], $validatedTranslation);
}
return $item;
}
Also, if you want legibility and go all out with functional programming, you could replace your loop with a collection method.
# Assuming the request object only has a translation array since you don't need the id anymore
public function update(MenuItem $item, UpdateMenuItemRequest $request)
{
collect($request->validated()['translations'])->each(function ($translation) use ($item) {
$item->translations()->updateOrCreate($translation);
});
}
Depending on what kind of relationship we're dealing with there could be other ways as well.