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

Laravel Resource Links Laravel Package

spatie/laravel-resource-links

Abandoned package that adds action URLs to Laravel API resources. Generate per-item and collection links (show/edit/update/delete, index/create/store) from a controller or defined actions, so resources include ready-to-use endpoints without manual URL building.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require spatie/laravel-resource-links
    

    Publish the config (if needed):

    php artisan vendor:publish --provider="Spatie\ResourceLinks\ResourceLinksServiceProvider"
    
  2. Basic Usage: Extend your JsonResource with the HasLinks trait:

    use Spatie\ResourceLinks\HasLinks;
    
    class UserResource extends JsonResource
    {
        use HasLinks;
    }
    
  3. First Use Case: Define a links() method in your resource to specify which links to include:

    public function links()
    {
        return [
            'self' => 'index',
            'show' => 'show',
            'create' => 'create',
            'edit' => 'edit',
        ];
    }
    

    The package will automatically resolve URLs based on your controller actions.


Implementation Patterns

Controller Integration

  1. Default Controller Mapping: The package assumes standard RESTful controller methods (index, show, store, update, destroy). If your controller follows this pattern, no additional configuration is needed.

  2. Custom Controller Actions: For non-standard action names (e.g., customAction), explicitly define them in the links() method:

    public function links()
    {
        return [
            'custom' => 'customAction',
        ];
    }
    
  3. Dynamic Link Generation: Use closures to dynamically generate links based on the resource:

    public function links()
    {
        return [
            'self' => fn() => route('users.show', $this->resource),
            'delete' => fn() => route('users.destroy', $this->resource),
        ];
    }
    

Resource-Level Configuration

  1. Global Defaults: Override defaults in config/resource-links.php:

    'default_links' => [
        'self' => 'index',
        'show' => 'show',
    ],
    
  2. Conditional Links: Use closures to conditionally include links:

    public function links()
    {
        return [
            'edit' => fn() => auth()->check() ? 'edit' : null,
        ];
    }
    
  3. Nested Resource Links: For nested resources (e.g., PostResource with comments link), use route parameters:

    public function links()
    {
        return [
            'comments' => 'posts.comments.index',
        ];
    }
    

API Response Integration

  1. Embedding Links in JSON:API: Combine with HasMeta for a complete API response:

    use Spatie\ResourceLinks\HasLinks;
    use Spatie\ResourceLinks\HasMeta;
    
    class UserResource extends JsonResource
    {
        use HasLinks, HasMeta;
    }
    
  2. Customizing Link Labels: Override the linkLabels() method to change link names in the response:

    protected function linkLabels(): array
    {
        return [
            'self' => 'user_self',
            'edit' => 'edit_profile',
        ];
    }
    

Gotchas and Tips

Common Pitfalls

  1. Controller Not Found: If the package can't resolve a route, ensure:

    • The controller method exists.
    • The route is properly defined in routes/api.php or routes/web.php.
    • The route name matches the action name (e.g., 'show' maps to show() in the controller).
  2. Circular Dependencies: Avoid circular references when dynamically generating links (e.g., self linking to show which links back to self). Use null or omit problematic links.

  3. Cached Routes: Clear route cache if links stop working:

    php artisan route:clear
    

Debugging Tips

  1. Inspect Generated Links: Temporarily dump the resolved links in your resource:

    public function links()
    {
        $links = $this->getLinks();
        dd($links); // Debug resolved URLs
        return $links;
    }
    
  2. Check Route Existence: Verify routes exist with:

    php artisan route:list
    
  3. Middleware Issues: If links fail silently, ensure your API routes are protected by the correct middleware (e.g., api or auth:api).

Extension Points

  1. Custom Link Resolvers: Extend the Spatie\ResourceLinks\LinkResolver class to handle custom logic:

    class CustomLinkResolver extends LinkResolver
    {
        public function resolve($action, $resource)
        {
            // Custom resolution logic
        }
    }
    

    Bind it in AppServiceProvider:

    ResourceLinks::resolver(new CustomLinkResolver());
    
  2. Override Default Behavior: Replace the HasLinks trait entirely by publishing and modifying the trait:

    php artisan vendor:publish --tag=resource-links-traits
    
  3. Localization: Localize link labels by overriding linkLabels() and using Laravel's translation system:

    protected function linkLabels(): array
    {
        return [
            'self' => __('resource_links.self'),
        ];
    }
    

Performance Considerations

  1. Avoid Over-Fetching: Only include necessary links in the links() method to reduce payload size.

  2. Lazy Loading: For large datasets, consider lazy-loading links via a separate endpoint or query parameter.

Workarounds for Abandoned Package

  1. Fork and Maintain: Fork the repository to apply fixes or updates if critical issues arise.

  2. Alternative Packages: Consider modern alternatives like:

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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport