Call to a member function templates() on null

  laravel, php

I present a modal to add products, everything is fine, it saves it and shows the products in the table, but when I do tests and I start to click to edit the modal appears all right, but I do that repeatedly with the other products and the following error:

"message": "Call to a member function templates() on null", "exception": "Error", "file": "C:UsersRastaX-ForceDocumentsGitHubet-templateappHttpControllersProductsController.php", "line": 40,

my the code of my function the controller is, this is line 40 that marks the error for me:

$tem = collect(Template::where('id', $prod->categories()->first()->templates()->first()->id)->first());

but still the function if you let edit and show the product

Source: Ask PHP