M
M
Martin Alekseevich2018-01-11 18:18:57
ORM
Martin Alekseevich, 2018-01-11 18:18:57

How to check the existence of records in the database?

I started learning Laravel and ran into a problem. There is the following code

/**
* @param int $category_id
* @param int $product_id
*
* @return JsonResponse
*/
public function destroy(int $category_id, int $product_id): JsonResponse
{
    $user = Auth::getUser();

    $category = $user->categories()->find($category_id);

    if (!$category) {
        return response()->json([
            'message' => 'Category not found.'
        ], 404);
    }

    $product = $category->products()->find($product_id);

    if (!$product) {
        return response()->json([
            'message' => 'Product not found.'
        ], 404);
    }

    $product->delete();

    return response()->json([
        'message' => 'Product deleted.'
    ], 200);
}

The question is how to simplify all checks for the existence of records with the corresponding id. I don't like the current version because of its verbosity and the fact that similar code is duplicated in several more actions. In Symfony, I would use @ParamConverter , but Laravel does not seem to have such a mega-handy thing.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Victor, 2018-01-11
@martin_alekseevich

Route Model Binding

A
Alex Wells, 2018-01-11
@Alex_Wells

There is something like this =)
But naturally, it will not magically find user categories by category, there is no such strong magic here.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question