M
M
Mykola Ivashchuk2018-09-27 11:57:32
Laravel
Mykola Ivashchuk, 2018-09-27 11:57:32

How to perform dependency injection in resource?

I am using resource to format the API response. Some
objects have links to files, and for these links you need to create a signature and a lifetime.
This action is performed by a class object, and I want to inject it like this:

class AttachmentResource extends JsonResource
{
    /**
     * @var S3Client
     */
    protected $s3Client;

    public function __construct($resource, S3Client $client)
    {
        parent::__construct($resource);
        $this->s3Client = $client;
    }

    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        $cmd = $this->s3Client->getCommand('GetObject', [
            'Bucket' => config('aws.bucket'),
            'Key'    => $this->url
        ]);
        $preSignedRequest = $this->s3Client->createPresignedRequest($cmd,'+1 year');
        return [
            'id' => $this->id,
            'url' => $preSignedRequest->getUri()
      ];
  }
}

But I am getting an error
Argument 2 passed to App\\Http\\Resources\\AttachmentResource::__construct() must be an instance of Aws\\S3\\S3Client, integer given, called in /var/www/vendor/laravel/framework/src/ Illuminate/Support/Collection.php on line 1039"

Passing data to a resource happens like this:
AttachmentResource::collection($this->attachments);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artyom, 2018-09-27
@mykolaim

In AppServiceProviderthe method registerwrite:

$this->app->when(AttachmentResource::class)
          ->needs(S3Client::class)
          ->give(S3Client::class);

Don't forget to write use for classes)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question