Passin args to laravel eloquent api resources constructor

Viewed 1424

How I can pass args to Laravel Eloquent API Resources constructor and get it to conditional data returning on response?

What I tried:

Controller

$user = User::find(1);
return new UserResource($user, $shortData = true);

API Resource:

public function toArray($request, $shortData)
{
    if($short) {
        return $shortData;
    } else {
        return $fullData;
    }
}
1 Answers

You have to do something like this :

  • Add the conditional data in your constructor (like you did). This conditional data can be null :
$user = User::find(1);
return new UserResource($user, $conditionalData);
  • Then in your UserResource, add the conditional data as a private attribute and add it to your constructor like this (it works as well with PHP default argument value...) :
private $conditionalData;

    public function __construct(User $resource, ?string $conditionalData)
    {
        parent::__construct($resource);
        $this->conditionalData = $conditionalData;
    }
public function toArray($request)
    {
        return [
            'data_1' => $this->data1,
            'data_2' => $this->data2,
            'conditional_data' => $this->when(!is_null($this->conditionalData), $this->$conditionalData)
        ];
    }

Your conditional data will be present in your response only if the attribute is not null.

Related