On laravel 10 site running phpstan on method
/**
* Retrieve user getItemss related to getItems by $itemId
*
* param int $itemId - getItems id
*
* @return JsonResponse with collection of found data,
*
*/
public function getItems(int $itemId): JsonResponse
{
try {
return response()->json([
'data' => ItemResource::collection($this->itemRepository->getItems(id: $itemId))
], JsonResponse::HTTP_OK); // 200
} catch (ModelNotFoundException $e) {
return response()->json([
'message' => 'Item # "' . $itemId . '" not found',
], JsonResponse::HTTP_INTERNAL_SERVER_ERROR);
} catch (Exception $e) {
\Log::info($e->getMessage());
}
}
But I have error pointing at try block line:
Method App\Http\Controllers\Api\ItemController::getItems() should return Illuminate\Http\JsonResponse but return statement is missing.
Not sure what have I return under last catch and in the end of the function to avoid any phpstan errors ?
"laravel/framework": "^10.34.2",
"nunomaduro/larastan": "^2.6.4",
Thanks in advance!
Static typing means your function should always return the type you specified no matter what the input value or path it takes, in your case, your method
getItemsalways expect to returnJsonResponseregardless of its internal logic, the end result must beJsonResponsetype,problem is when your 2nd catch block is hit, it does not return anything (just returns void)
you could simply just do something like;
To avoid unused variables
another option with single return statement at the end of the function, and just mutating the variable inside try/catch block
or with each block has return statement no variables defined!