christopherarter / laravel-resourceable

A handy method for getting a Model's API resource as an array.
MIT License
2 stars 1 forks source link

Can't find the Resource class associated with the model. #1

Open aman-plugenergy opened 3 hours ago

aman-plugenergy commented 3 hours ago

First off, really handy piece of code to help with faster testing.

I was trying this out in Laravel 11 and php 8.3 and it's not working as expected.

To clarify, I have a User model in app/Model/User.php and a Resource defined for it in app/Http/Resources/UserResource.php. Even though a resource class is defined, it isn't picked up by default when I use the toResourceArray() method. So, I end up getting the model turned into an array as a response, instead of it using the Resource class automatically.

After checking it seems the namespace is incorrect, which is why the resource can't be found. Specifically, in the trait Resourceable, within the resolveResourceName() method we have these line:

$reflect = new \ReflectionClass($this);
return "\\{$reflect->getNamespaceName()}\\Http\\Resources\\{$reflect->getShortName()}Resource";

The problem seems to be the getNamespaceName() method as it returns the full namespace as App\Models. This means the return value of the function resolveResourceName() method becomes (in this example with the User model):

\App\Models\Http\Resources\UserResource

This obviously doesn't exists and so the check in toResourceArray() fails and it defaults to convert the Eloquent model to array without using the Resource class.

A simple fix is:

(-)  return "\\{$reflect->getNamespaceName()}\\Http\\Resources\\{$reflect->getShortName()}Resource";
(+) return "\\App\\Http\\Resources\\{$reflect->getShortName()}Resource";

Ofcourse I am not sure if there are some other considerations for using the getNamespaceName() method.

Would love to hear your thoughts.

lattaai13 commented 3 hours ago

Hello, I tried to solve the issue.

This is what I did:

Modified the resolveResourceName() method in the Resourceable trait to correctly resolve the namespace for Laravel 11 and PHP 8.3. This change ensures that the Resource class is properly located and used when calling toResourceArray().

You can review changes in this commit: https://github.com/lattaai13/christopherarter-laravel-resourceable-1/commit/7ed18bce01fce0d183f4398eca191b40bf5fda45.

[!CAUTION] Disclaimer: The commit was created by Latta AI and you should never copy paste this code before you check the correctness of generated code. Solution might not be complete, you should use this code as an inspiration only.


This issue was tried to solve for free by Latta AI - https://latta.ai/ourmission

If you no longer want Latta AI to attempt solving issues on your repository, you can block this account.