0

Will it be correct, if I create API RESOURCES for each request. And how to make a connection between three tables in Resources. For example:

class UserResource
public function toArray($request)
{
    return [
       'id'=>$this->id,
       'name'=>$this->name
       'work'=>WorkResource::collection($this->work)//relationship between USER and WORK
    ]
}
class WorkResource
public function toArray($request)
{
    return [
       'id'=>$this->id,
       'title'=>$this->title
    ]
}

And in class UserResource I need to return from WORK only TITLE without ID, How I can do that?

Pardeep
  • 2,153
  • 1
  • 17
  • 37
Aleks
  • 147
  • 10

1 Answers1

0

I'm not sure if I got it right but $this->work seems singular while you are instanciating the resource using Resource::collection(). So my guess would be:

class UserResource
{
    public function toArray($request)
    {
        return [
            'id'   => $this->id,
            'name' => $this->name,
            'work' => new WorkResource($this->whenLoaded('work'))
        ];
    }
}

class WorkResource
{
    public function toArray($request)
    {
        return [
            'title' => $this->title
        ];
    }
}
Alessandro Benoit
  • 903
  • 10
  • 19
  • ok, thank you. And in a query, I wrote - WITH, but how I can take only one field? For example: title. And Must I create for each request - different resources – Aleks Sep 25 '19 at 07:36
  • Well, using resources you limit the output to the fields declared in the `toArray` method. If you're looking to query the database for only the given fields you can find more info here https://stackoverflow.com/questions/19852927/get-specific-columns-using-with-function-in-laravel-eloquent. Also, I'm not sure what you mean for "Must I create for each request - different resources", that's up to you, but unless it makes the code much more readable you should stay DRY (https://en.wikipedia.org/wiki/Don%27t_repeat_yourself). Please accept my answer if it fully replies your question. – Alessandro Benoit Sep 25 '19 at 08:51