Skip to main content

MetadataResource

The MetadataResource class transforms Meta model instances into JSON responses for API endpoints. It automatically handles JSON decoding for complex values.

Namespace​

JobMetric\Metadata\Http\Resources\MetadataResource

Overview​

The MetadataResource is a JSON resource that formats metadata for API responses. It automatically decodes JSON values and returns metadata in a clean key-value format.

Basic Usage​

Single Metadata​

use JobMetric\Metadata\Http\Resources\MetadataResource;
use JobMetric\Metadata\Models\Meta;

$meta = Meta::find(1);
return new MetadataResource($meta);

// Response:
// {
// "color": "red"
// }

Metadata Collection​

$metas = $product->metas;
return MetadataResource::collection($metas);

// Response:
// [
// { "color": "red" },
// { "size": "large" },
// { "dimensions": { "width": 10, "height": 20 } }
// ]

Resource Structure​

The resource returns metadata in the following format:

{
"key": "value"
}

For JSON values, the value is automatically decoded:

{
"dimensions": {
"width": 10,
"height": 20
}
}

Complete Examples​

Controller Response​

namespace App\Http\Controllers;

use App\Models\Product;
use JobMetric\Metadata\Http\Resources\MetadataResource;

class ProductMetadataController extends Controller
{
public function index(Product $product)
{
$metas = $product->metas;
return MetadataResource::collection($metas);
}

public function show(Product $product, string $key)
{
$meta = $product->metaKey($key)->first();

if (!$meta) {
return response()->json(['error' => 'Metadata not found'], 404);
}

return new MetadataResource($meta);
}
}

With Pagination​

public function index(Product $product)
{
$metas = $product->metas()->paginate(15);
return MetadataResource::collection($metas);
}