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.

\$\endgroup\$
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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.