1
\$\begingroup\$

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.

asked Mar 12, 2019 at 9:04
\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

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.

Toby Speight
87.1k14 gold badges104 silver badges322 bronze badges
answered Oct 16, 2019 at 16:43
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.