-
Upgrading from Laravel 9 to 10, I encountered an issue when trying to use toArray() method on a resource collection. In Laravel 9, passing a 0 argument worked, but in Laravel 10, I get an error saying that the $request parameter must be of type Illuminate\Http\Request. I found that passing request() works, but is there a better way to handle this issue? Is there a recommended approach for using toArray() in Laravel 10 that I might be missing?
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
For those who might be facing a similar issue, the problem was related to the fact that in Laravel 10, the toArray method in Eloquent resources no longer accepts an integer parameter like in Laravel 9. Instead, you need to pass a request object to it. One possible solution suggested in Laravel Discord by @ Tippin was to use the resolve method to get the array representation of the resource without having to pass a request object to the toArray method. Here's an example:
This approach should work in both Laravel 9 and Laravel 10. |
Beta Was this translation helpful? Give feedback.
For those who might be facing a similar issue, the problem was related to the fact that in Laravel 10, the toArray method in Eloquent resources no longer accepts an integer parameter like in Laravel 9. Instead, you need to pass a request object to it.
One possible solution suggested in Laravel Discord by @ Tippin was to use the resolve method to get the array representation of the resource without having to pass a request object to the toArray method. Here's an example:
This approach should work in both Laravel 9 and Laravel 10.
https://github.com/laravel/framework/blob/10.x/src/Illuminate/Http/Resources/Json/JsonResource.php#L105-L118