Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

asi_lh's avatar

Validate or not API calls

What is more proper way to build own API, create simple ass possible CRUD actions like:

public function show($id) {
    return Users::findOrFail($id);
}

or with validation ant try catch blocks like bellow:

public function show($id)
{
    if (!filter_var($id, FILTER_VALIDATE_INT)) {
        return response()->json([
            'message' => 'Please provide int value'
        ], 400);
    }

    $user = null;
    try {
        $user = new UserResource(User::find($id));
    } catch (\Exception $e) {
        return response()->json([
            'message' => 'Failed to fetch data'
        ], 404);
    }

    if (is_null($user->resource)) {
        return response()->json([
            'message' => 'Resource not found'
        ], 404);
    }

    return $user;
}
0 likes
2 replies
bobbybouwmann's avatar

Yeah, the try catch is very useful in this case, because if something goes wrong you to know the user of the api what went wrong. But the api itself is not more than crud actions, but instead of returning views you return json or in your case resources.

You also can move your validation of the api to request classes: https://laravel.com/docs/5.8/validation#form-request-validation

Please or to participate in this conversation.