PHP code example of dandoetech / laravel-resource-registry
1. Go to this page and download the library: Download dandoetech/laravel-resource-registry library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
dandoetech / laravel-resource-registry example snippets
declare(strict_types=1);
namespace App\Resources;
use DanDoeTech\ResourceRegistry\Resource;
use DanDoeTech\ResourceRegistry\Builder\ResourceBuilder;
use DanDoeTech\ResourceRegistry\Definition\FieldType;
use DanDoeTech\LaravelResourceRegistry\Contracts\HasEloquentModel;
use DanDoeTech\LaravelResourceRegistry\Contracts\HasPolicy;
class ProductResource extends Resource implements HasEloquentModel, HasPolicy
{
public function model(): string { return \App\Models\Product::class; }
public function policy(): string { return \App\Policies\ProductPolicy::class; }
protected function define(ResourceBuilder $b): void
{
$b->key('product')
->label('Product')
->timestamps()
->field('name', FieldType::String, nullable: false, rules: ['
use DanDoeTech\ResourceRegistry\Registry\Registry;
$registry = app(Registry::class);
$product = $registry->getResource('product');
echo $product->getLabel(); // "Product"
foreach ($registry->all() as $resource) {
echo $resource->getKey();
}
return [
// Directories scanned for Resource classes (relative to base_path)
'resource_paths' => [
'app/Resources',
'Modules/*/Resources',
],
];
// Link resource to an Eloquent model
interface HasEloquentModel
{
/** @return class-string<Model> */
public function model(): string;
}
// Link resource to a Laravel policy
interface HasPolicy
{
/** @return class-string */
public function policy(): string;
}
// Scope queries to the authenticated user's records
interface HasOwnerScope
{
public function ownerKey(): string;
}
// @deprecated — use HasOwnerScope or Policies instead (removed in v1.0)
interface HasScope
{
/** @return class-string|Closure|null */
public function scope(): string|Closure|null;
}
$modelClass = $resource instanceof HasEloquentModel
? $resource->model()
: throw new \RuntimeException("No model for '{$resource->getKey()}'");
use DanDoeTech\LaravelResourceRegistry\Contracts\EloquentComputedResolverInterface;
use Illuminate\Database\Eloquent\Builder;
class CompletedOrdersCount implements EloquentComputedResolverInterface
{
public function apply(Builder $query): Builder
{
return $query->withCount(['orders as completed_orders' => fn ($q) =>
$q->where('status', 'completed')
]);
}
public function filter(Builder $query, mixed $value, string $operator = '='): Builder
{
return $query->having('completed_orders', $operator, $value);
}
public function sort(Builder $query, string $direction): Builder
{
return $query->orderBy('completed_orders', $direction);
}
}