1

I am trying to store heavy image through the laravel queue as follows because i dont want my user to wait until file gets stored:

This code is in controller

if($request->hasfile('featuringPhoto')) 
        {
            $prefixFilename = date("Y-m-d-H-i-s");
            $coverFilename = $prefixFilename.$request->featuringPhoto->getClientOriginalName();
            
            ProceessFiles::dispatch($request->featuringPhoto->getRealPath(),$coverFilename);
            
        }
        else
        {
            $coverFilename4 = NULL;
        }

Below code is in job

protected $files, $filename;

public function __construct($files,$filename)
    {
        $this->files= $files;
        $this->filename = $filename;
    }

public function handle()
    {
        if($this->files){
            
         
          $coverFilename = $prefixFilename.$this->filename;
          $img = file_get_contents($this->files);
    
          $img->storeAs('images/photosUploadedByUser', $coverFilename, 'public');
      
        }
    }

It Gives me an error saying Call to a member function storeAs() on string I tried this solution from stack but didnt work

Any suggestion will be appreciated.Thank you.

Priyanka
  • 83
  • 6
  • make sure you added `enctype='multipart/form-data'` – STA Mar 26 '22 at 05:09
  • yes it is there in view. Thank you. – Priyanka Mar 26 '22 at 05:10
  • What do you have for @img? Is that the file content? – Kevin Bui Mar 26 '22 at 05:13
  • yes it is an image uploaded by user as you can see in the I'm passing this $request->featuringPhoto->getRealPath() as a parameter. – Priyanka Mar 26 '22 at 05:15
  • 1
    Why do you think that saving the image takes too much time? When the file has been uploaded it is already held in a temporary file before your controller is called. All that happens in storeAs is the image is moved from one folder to another. This takes no time at all. – Snapey Mar 26 '22 at 10:49
  • Yeah agreed but can you help me here, what am i doing wrong here? – Priyanka Mar 26 '22 at 13:07

1 Answers1

1

I think it is wrong to assume you are gonna save a lot time by executing the save operation in a queue, also because you are already fetching it from the web server. Queues will with scaling often be moved to worker servers and with this approach this will not work.

In the spirit of the question, stackoverflow and to explain to you what is not working. file_get_contents() returns the content of the file as a string. So to fix your problem, you should just store the results of that. You obviously can not call methods on strings.

$coverFilename = $prefixFilename.$this->filename;
$img = file_get_contents($this->files);
Storage::put('images/photosUploadedByUser/' . $coverFilename, $img);
mrhn
  • 17,961
  • 4
  • 27
  • 46