I have a model called UserCar defined in this way
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class UserCar extends Model
{
protected $table = 'user_cars';
protected $fillable = ['id','name','model_id','fuelType','....','user_id'];
public function modelo() {
return $this->hasOne(CarModel::class,'id','model_id');
}
}
And my intention is when obtaining the result of an item, to make use of a Resource to be able to add dynamic fields if necessary or to process the data
Resource UserCar
class UserCarResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'name' => $this->name . ' test test',
'model_name' => $this->name . ' test test',
'model_id' => $this->model_id,
'model_text' => 'model name',
'fuelType' => $this->fuelType,
'fuelType_text' => 'Gasolina',
'yearFabrication' => $this->yearFabrication,
'potency' => $this->potency,
'enabled' => $this->enabled,
];
}
}
And then to make use of it, I do it this way
$car = UserCarResource::collection(UserCar::where('id',$id)->get());
dd($car);
I see that it returns me a UserCarResource, but I don't see that it returns me, for example, the "model_name" property that I expressly create in the resource, or the name that I expressly create in the resource in this way "'name' => $this->name .' test test'," concatenating "test test" as I don't see it in the resource sample.
This happens because it
toArray()
is only called when it is returned as a response. If you read the documentation :If a resource is passed to a view (which is not a
respuesta
), it will not call thetoArray()
. However, you can access the methodtoArray()
manually.If you want to transform your Model, you should use Transformers . Since resources shouldn't be used this way.