Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Entity relationships #9

Closed
thecko opened this issue Jun 25, 2020 · 1 comment
Closed

Entity relationships #9

thecko opened this issue Jun 25, 2020 · 1 comment

Comments

@thecko
Copy link

thecko commented Jun 25, 2020

Hello,

I'm using your repo as a guide to make an API and I have a doubt. Hope you can help me.

When you have a related entity. For example, if the Book Author is another Author model. What's the best approach?
Now what I'm doing is in the BookResource, use 'author' => new AuthorResource( $this->author ). It works, and it shows the information, but I suposse I'll have problems with recursivity easily.

Is there any feature like a "link"? I mean, in author show a link to the resource to get the author data like "API URL/authors/12".

Many thanks

@Tony133
Copy link
Owner

Tony133 commented Jun 25, 2020

Hello

If you have to relate entities it is certainly better to use laravel resources which are a great thing, since when I use them I have been able to do better relationships between bees.

While for the "link" functions you should do a collection of resources something like:

class BookCollection extends ResourceCollection
{
    /**
     * Transform the resource collection into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'data' => $this->collection,
            'links' => [
                'self' => 'link-value',
            ],
        ];
    }
}

or you can use this package: https://github.com/spatie/laravel-resource-links
while this is a tutorial: --> https://freek.dev/1470-a-package-that-adds-resource-links-to-your-laravel-api-resources
Using this package you have the "links" method to make the link.

this package is also interesting: --> https://github.com/gdebrauwer/laravel-hateoas

I also leave you the link of another repo that I have made of example with the resources of laravel:
https://github.com/Tony133/LaravelAPIBoilerplateJWTBook

I hope I was helpful

for anything write to me 😀

Tony

@Tony133 Tony133 closed this as completed Jun 25, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants