Laravel 5.6 - Pass additional parameters to API Resource?
This is how I made it on laravel 8.
class PatientResource extends JsonResource
{
private static $data;
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
//access $data
//self::$data
return [
'id' => $this->id,
'first_name' => $this->first_name,
'middle_name' => $this->middle_name,
'last_name' => $this->last_name,
'contact_number' => $this->contact_number
];
}
//I made custom function that returns collection type
public static function customCollection($resource, $data): \Illuminate\Http\Resources\Json\AnonymousResourceCollection
{
//you can add as many params as you want.
self::$data = $data;
return parent::collection($resource);
}
}
Then on my controller I called that custom function.
$data = PatientResource::customCollection($query->get(),$medicines);
The following approach worked for me:
UserResource
class UserResource extends Resource{
protected $foo;
public function foo($value){
$this->foo = $value;
return $this;
}
public function toArray($request){
return [
'id' => $this->id,
'name' => $this->name,
'foo' => $this->foo,
];
}
public static function collection($resource){
return new UserResourceCollection($resource);
}
}
UserCollection
class UserResourceCollection extends ResourceCollection{
protected $foo;
public function foo($value){
$this->foo = $value;
return $this;
}
public function toArray($request){
return $this->collection->map(function(UserResource $resource) use($request){
return $resource->foo($this->foo)->toArray($request);
})->all();
// or use HigherOrderCollectionProxy
// return $this->collection->each->foo($this->foo)->map->toArray($request)->all()
// or simple
// $this->collection->each->foo($this->foo);
// return parent::toArray($request);
}
}
Different ways to pass the additional parameter
(new UserResource($user))->foo('bar');
(new UserResourceCollection($user))->foo('bar');
UserResource::make($user)->foo('bar');
UserResourceCollection::make($users)->foo('bar');
UserResource::collection($users)->foo('bar');