Absolutely, you can use Laravel API Resources for data that isn't tied directly to Eloquent models! Resources are really just transformers — you feed them any array or object, and they output a consistent, formatted response for your API.
How?
You can instantiate a resource with plain PHP arrays, collections, or any object — it doesn't have to be an Eloquent model. The same pattern applies if you're building an aggregate array or merging output from multiple models.
Example: Resource with Non-Model Data
// In app/Http/Resources/CustomResource.php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class CustomResource extends JsonResource
{
public function toArray($request)
{
return [
'foo' => $this['foo'],
'bar' => $this['bar'],
];
}
}
Then in your controller:
use App\Http\Resources\CustomResource;
public function showCustomData()
{
$aggregatedData = [
'foo' => 'hello',
'bar' => 'world',
];
return new CustomResource($aggregatedData);
}
Or for a collection of plain arrays:
use Illuminate\Support\Collection;
use App\Http\Resources\CustomResource;
public function index()
{
$data = collect([
['foo' => 'a', 'bar' => 1],
['foo' => 'b', 'bar' => 2],
]);
return CustomResource::collection($data);
}
Wrapping Data in a Custom Top-Level Structure
If you want all responses to have { success, message, data }, you can:
1. Use with() method in the Resource
public function with($request)
{
return [
'success' => true,
'message' => 'OK',
];
}
This will wrap every resource response:
{
"data": { /* your payload */ },
"success": true,
"message": "OK"
}
2. Or, Override the toArray entirely
You can override the toArray($request) method to customize the entire response shape:
public function toArray($request)
{
return [
'success' => true,
'message' => 'Fetched successfully',
'data' => parent::toArray($request), // or use your own custom structure
];
}
Summary:
Resources can transform any data — not just Eloquent models! Array, Collection, custom objects, even plain PHP arrays; if you pass it in, Resource will handle it.
References: