Notification texts go here Contact Us Buy Now!

Why is this ResourceCollection not working?

Route::get('/orders/bulkindex/', function () {
   return OrderResource(Order::all());
});
The error message "Call to undefined method Illuminate\Http\Resources\Json\JsonResource::collection()" suggests that you are trying to use the `::collection()` method on the `OrderResource` class, which is incorrect. In Laravel, you should not call the `::collection()` method on resource classes. Instead, pass an Eloquent model collection directly to the constructor of the resource. Here's a corrected version of your code:
Route::get('/orders/bulkindex/', function () {
   return new OrderResource(Order::all());
});
In this code, we create a new instance of the `OrderResource` class, passing the `Order::all()` collection to its constructor. This will create a JSON response with the data from the `Order` collection, using the structure defined in the `OrderResource` class. Here's an example from the Laravel documentation:
use App\Http\Resources\UserCollection;
use App\User;

Route::get('/users', function () {
    return new UserCollection(User::all());
});
In this example, the `UserCollection` resource collection is used to return a JSON response with the data from the `User` collection. Remember, the `::collection()` method should only be used when creating a resource collection from an array or another collection that is not an Eloquent model collection.

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.