alihoushyaripour
1 year ago
117
6
Laravel

How to pass additional parameters to resource class?

Posted 1 year ago by alihoushyaripour

Hi,

I want to pass additional parameters to this resource class because I need to find this resource class called from where controller, see these:

// resource class
class GiftResource extends Resource
{
    public function toArray($request)
    {
        return [
            'id' => (integer)$this->id,
            'title' => substr($this->title, 0, 150),
            'description' => (string)$this->description,
            'image' => (string)$this->image,
            'from' => (string)$this->additional->from, //here
        ];
    }

    // additional
    public $additional;

    function additional(array $data)
    {
        return parent::additional($data); // TODO: Change the autogenerated stub
    }

    /**
     * @return array
     */
    public function getAdditional(): array
    {
        return $this->additional;
    }

    /**
     * @param mixed $additional
     */
    public function setAdditional($additional)
    {
        $this->additional = $additional;
    }

}

user controller:

class UserController extends Controller
{
    public function getById($id)
    {
        // get user

        // get user gift
        $gift = $giftService->getByUserId($id);
        $gift = GiftResource::collection($gift)->additional(['from' => 'UserController']); //here

        ...
    }
}

place controller:

class PlaceController extends Controller
{
    public function getById($id)
    {
        // get place

        // get place gift
        $gift = $giftService->getByPlaceId($id);
        $gift = GiftResource::collection($gift)->additional(['from' => 'PlaceController']); //here

        ...
    }
}

I've heard that exist a parameter with name additional that it's duty is save additional parameters in itself, but this not work and always additional is null.

anyone can help me?

Please sign in or create an account to participate in this conversation.