Attempt to read property "id" on string in Laravel API: Diagnosing Type Mismatch in Resource Collection
When debugging an ApiResource error like "message": "Attempt to read property "id" on string", the immediate reaction is often to check model relationships or cast attributes. However, looking at the specific stack trace pointing to a custom resource file reveals a much more fundamental issue: a logic error in how the collection is being passed to the formatter.
The root cause lies in the interaction between the controller and the ProductResource class. In your ProductController, you are correctly querying the database using Eloquent's pagination methods:
$products = Product::offset($offset)->limit($limit)->get();
return new ProductResource($products);
Here, $products is an instance of Illuminate\Database\Eloquent\Collection. This collection contains multiple model instances. The error occurs because the constructor of your ProductResource accepts this collection, but the internal logic inside toArray() treats the input as a single request object rather than a collection of items.
The Type Mismatch in toArray()
The specific line causing the crash is:
foreach ($request->all() as $product) {
// ... access $product->id ...
}
In JsonResource, the toArray method receives the first argument (usually named $resource) which represents the data you are formatting. When you instantiate the resource with new ProductResource($products), that collection is stored as the resource instance. However, inside your toArray method, you are calling $request->all().
In this context, $request refers to the HTTP Request object passed to the resource constructor, not the data collection you intended to loop through. Since an HTTP Request object does not have an id property on its items (and certainly doesn't behave like a collection of models), attempting to access $product->id where $product is actually a string or null results in the "read property on string" error.
Correcting the Resource Logic
To fix this, you need to loop over the actual data passed to the resource, not the request object itself. If you are passing a collection of models, iterate directly over that argument.
Here is the corrected implementation:
class ProductResource extends JsonResource
{
public function __construct($products)
{
parent::__construct();
// Ensure we store the collection for later use if needed,
// or simply rely on the standard constructor behavior.
}
public function toArray($request)
{
$response = [];
// Iterate over the resource instance (the collection), not $request->all()
foreach ($this->toArrayCollection() as $product) {
$response[] = [
'id' => $product->id, // Ensure this is an integer or string ID
'name' => $product->name,
'slug' => $product->slug,
'regular_price' => $product->regular_price,
'sale_price' => $product->sale_price,
'SKU' => $product->SKU,
'stock_status' => $product->stock_status,
'quantity' => $product->quantity,
'image' => $product->url,
'images' => $product->url,
'category_id' => $product->category_id,
];
}
return response($response);
// Note: Return a standard Response or use JsonResource::make()
// to maintain consistency with other API responses.
}
}
However, there is an even simpler and more idiomatic approach in Laravel. Instead of manually looping and building an array inside toArray, you can let the framework handle the transformation for each item automatically:
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'slug' => $this->slug,
'regular_price' => $this->regular_price,
'sale_price' => $this->sale_price,
'SKU' => $this->SKU,
'stock_status' => $this->stock_status,
'quantity' => $this->quantity,
'image' => $this->url,
'images' => $this->url,
'category_id' => $this->category_id,
];
}
By doing this, the JsonResource base class automatically iterates over the collection passed to it and applies the toArray logic to each model instance. This is less error-prone than manually looping.
Handling Pagination Response
You also return a 201 Created status code (return response($responses, 201)), which might not be semantically correct for a standard GET request listing products. Unless you are actually creating a resource via POST and returning the collection of created items (which is rare), a 200 OK or simply using the resource's built-in collection handling (return new self($products)) is more appropriate.
For pagination, ensure you don't manually construct the array if you want standard Laravel paginated responses. You can return the raw collection and let the framework handle the meta-data, or explicitly define the structure for a flat list:
public function index(Request $request)
{
$limit = $request->has('limit') ? $request->get('limit') : 10;
$offset = $request->has('offset') ? $request->get('offset') : 0;
$products = Product::offset($offset)->limit($limit)->get();
// Return the resource directly to leverage automatic collection mapping
return new ProductResource($products);
}
Summary of Fixes
- Stop accessing
$request->all(): The variable insidetoArrayis the HTTP request, not your data collection. Use the resource instance ($this) or the argument passed to the constructor to access items. - Leverage Built-in Collection Mapping: Avoid manual
foreachloops unless you have complex logic per item. Laravel'sJsonResourcehandles collections natively when you define properties on$this. - Verify Status Codes: Ensure your response status code matches the HTTP method (GET usually returns
200, not201).
By aligning your resource class with Laravel's standard patterns, you eliminate type mismatches and ensure that every model instance is correctly transformed into a JSON object before being sent to the client.