Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Resource Laravel Package

ekyna/resource

Laravel package providing a Resource layer with controllers, forms, validation, persistence and admin-style CRUD tooling. Helps structure domain resources consistently across your app and speeds up building back-office interfaces.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require ekyna/resource
    

    Publish the config (if available) with:

    php artisan vendor:publish --provider="Ekyna\Resource\ResourceServiceProvider"
    
  2. Basic Usage The package provides a Resource class for transforming Eloquent models into standardized API responses. Start by creating a custom resource class:

    use Ekyna\Resource\Resource;
    
    class UserResource extends Resource
    {
        public function toArray($request)
        {
            return [
                'id' => $this->id,
                'name' => $this->name,
                'email' => $this->email,
            ];
        }
    }
    
  3. First Use Case Transform a model in a controller:

    use Ekyna\Resource\UserResource;
    
    public function show(User $user)
    {
        return new UserResource($user);
    }
    

Implementation Patterns

Core Workflow

  1. Resource Classes Extend Ekyna\Resource\Resource for each model. Keep them in app/Http/Resources (or similar). Example:

    class PostResource extends Resource
    {
        public function toArray($request)
        {
            return [
                'title' => $this->title,
                'content' => Str::limit($this->content, 200),
                'author' => new UserResource($this->author),
            ];
        }
    }
    
  2. Nested Resources Use nested resource classes for relationships:

    class CommentResource extends Resource
    {
        public function toArray($request)
        {
            return [
                'body' => $this->body,
                'user' => new UserResource($this->user),
            ];
        }
    }
    
  3. Collections Extend Ekyna\Resource\ResourceCollection for collections:

    class PostCollection extends ResourceCollection
    {
        public function toArray($request)
        {
            return $this->collection->map->toArray($request);
        }
    }
    
  4. Request-Driven Fields Use $request to conditionally include fields:

    public function toArray($request)
    {
        return [
            'name' => $this->name,
            'email' => $request->has('include_email') ? $this->email : null,
        ];
    }
    
  5. API Responses Return resources directly from controllers:

    public function index()
    {
        return new PostCollection(Post::all());
    }
    

Integration Tips

  • API Routes: Pair with Laravel’s API resources for consistency.
  • Testing: Mock resources in unit tests:
    $resource = new UserResource(factory(User::class)->make());
    $this->assertEquals('John', $resource->name);
    
  • Caching: Cache resource responses in middleware if needed:
    public function handle($request, Closure $next)
    {
        $response = $next($request);
        if ($request->wantsJson()) {
            Cache::put('resource:' . $request->path(), $response);
        }
        return $response;
    }
    

Gotchas and Tips

Pitfalls

  1. Missing toArray Method Forgetting to implement toArray() will throw MethodNotAllowedHttpException. Always override it.

  2. Circular References Nested resources with circular relationships (e.g., User->posts->user) will cause infinite recursion. Use null or break cycles:

    public function toArray($request)
    {
        return [
            'posts' => PostResource::collection($this->posts)->except('user'),
        ];
    }
    
  3. Request Scope Resources rely on the $request object. Ensure it’s passed correctly in non-HTTP contexts (e.g., queues, commands). Use a mock request:

    $resource = new UserResource($user, new Request());
    
  4. No Built-in Pagination The package doesn’t include pagination. Use Laravel’s LengthAwarePaginator or SimplePaginator manually:

    return new PostCollection(Post::paginate(10));
    

Debugging

  • Inspect Output: Dump the resource array to debug:
    dd((new UserResource($user))->toArray(new Request()));
    
  • Check Request: Verify the $request object is accessible in toArray():
    dd($request->all()); // Debug request data
    

Extension Points

  1. Customize Resource Class Override Resource to add global behavior:

    class CustomResource extends Ekyna\Resource\Resource
    {
        public function toArray($request)
        {
            $array = parent::toArray($request);
            $array['meta'] = ['timestamp' => now()->toIso8601String()];
            return $array;
        }
    }
    
  2. Add Metadata Include metadata in responses:

    public function toArray($request)
    {
        return [
            'data' => $this->transformData(),
            'meta' => [
                'created_at' => $this->created_at->format('Y-m-d'),
            ],
        ];
    }
    
  3. Conditional Loading Lazy-load relationships to improve performance:

    public function toArray($request)
    {
        $this->loadMissing('posts.comments');
        return [
            'posts' => PostResource::collection($this->posts),
        ];
    }
    
  4. API Versioning Use request-based versioning in toArray():

    public function toArray($request)
    {
        if ($request->bearsToken('api-v2')) {
            return $this->toArrayV2();
        }
        return $this->toArrayV1();
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver