I want (for project reason), to create an array in a class controller and pass it to a resource. Consider in my controller class this method:
public function getExample(){
$attribute=array('otherInfo'=>'info');
return new ExampleResource($attribute);
}
and I in my class I would write sominthing like ExampleResource with:
public function toArray($request){
return[
'info' => $this->info
];
}
How I can convert the value $attribute to perform this operation return new ExampleResource($attribute);
?
Please do not suggest me to insert the field info in the model, this attribute can came from only from the external, from the controller and do not belong to the model in database.
class ExampleResource extends Resource
{
private $info;
/**
*
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function __construct($info)
{
$this->$info = $info;
}
public function toArray($request)
{
return[
'info'=>$this->$info,
'id' => $this->id
];
}
}
Add constructor to the resource class:
public function __construct($resource, $attribute)
{
$this->resource = $resource;
$this->attribute = $attribute;
}
Then in toArray()
:
return [
'info' => $this->attribute,
'created' => $this->created_at
];
And use it:
return new ExampleResource(Model::find($id), $attribute);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With