Reputation: 1293
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
];
}
}
Upvotes: 7
Views: 16367
Reputation: 163758
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);
Upvotes: 8
Reputation: 1194
Resources are intended to be used to easily transform your models into JSON.
Take a look at this example:
use App\User;
use App\Http\Resources\UserResource;
Route::get('/user', function () {
return new UserResource(User::find(1));
});
You just want to return an array of data so you should just return the array, it will be automatically turned into JSON:
Route::get('/info', function () {
return ['info' => 'info ...'];
});
For more informations check the docs here
Upvotes: 0