asi_lh
121
2
Lumen

Validate or not API calls

Posted 1 month ago by asi_lh

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;
}

Please sign in or create an account to participate in this conversation.