1

In laravel 9 I have ProductCardReport component which is on blade form and data are retrieved from ReportProduct class. I got data with firstOrFail in this class and I failed to catch this error in controller block. I have in ProductController controller :

public function showReport(string $productId)
{
    try {
        return view('admin/products/report', [
            'productId' => $productId,
        ]);
    } catch (ModelNotFoundException $e) { // I EXPECTED THIS BLOCK WOULD WORK
        \Log::info('-1ModelNotFoundException:');
        return redirect(route('admin.products.edit', $this->productId))
            ->with('message', 'Product "' . $this->productId . '" not found.')
            ->with('message_type', 'error');
    } catch (Exception $e) {
        \Log::info('-1 ProductCardReport -2 showReport $e->getMessage() ::' . print_r($e->getMessage(), true));

        return back()->withErrors(['message' => $e->getMessage()]);
    }

}

In view 'admin/products/report' I set component :

<x-app-layout>

    <x-product-card-report product-id="{{ $productId }}" />

</x-app-layout>

and in component app/View/Components/ProductCardReport.php :

public function render()
{
    $reportProduct = new ReportProduct();

    $itemRetrieved = $reportProduct->retrieveItem( id : $this->productId );
    ...
}

And in app/Library/ReportProduct.php I get data with invalid ID :

class ReportProduct implements ReportRetrieveItemInterface,  ReportDownloadItemInterface
{

    public function __construct()
    {
        $uploadedFileManagement= app(UploadedFileManagementInterface::class);
        $this->uploadedFileManagement = $uploadedFileManagement;
    }

    public function retrieveItem(string $id, array $getRelatedData = []) : bool
    {
        $this->product = Product
            ::getById($id .'ERROR') // ModelNotFoundException is raised here.
            ->firstOrFail();

But I got uncaught error :

Illuminate\Database\Eloquent\ModelNotFoundException
No query results for model [App\Models\Product].

and try block in ProductController did not work. How it can be fixed ?

Thanks!

mstdmstd
  • 2,195
  • 17
  • 63
  • 140
  • 2
    The function `view..` will not fail because `render` is not called when the view response is generated. `render` is called when the response is sent to the client which happens after the controller returns. You can try finding the model in the component constructor instead. – apokryfos Nov 05 '22 at 07:39

0 Answers0