Search code examples
phplaravelqueuejobs

How to pass the model to the Job/Queue for manipulating image


I have a PhotoController that scan a directory and foreach images create a new record in a database and dispatch a job to manipulate the image, but can't make the job work!

Here the Photo Model:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Photo extends Model
{
    protected $table = "photos";

    protected $fillable = [
        'org_path'
    ];
}

Here the PhotoController:

namespace App\Http\Controllers;

use App\Photo;

use App\Jobs\ProcessImage;


class PhotoController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        // Get Photos inside the private folder org_folder
        $org_images = preg_grep('~\.(jpeg|jpg|png)$~', scandir(storage_path('app/images/')));

        foreach ($org_images as $image) {

            $post = new Photo;
            $post->org_path = storage_path('app/images/').$image;
            $post->pub_path = NULL;
            $post->save();

            $this->dispatch(new ProcessImage($post));

        }

    }

}

Here the Job:

namespace App\Jobs;

use Illuminate\Bus\Queueable;  
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

use Image;
use App\Photo;

class ProcessImage implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable,     SerializesModels;

    protected $post;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(Photo $post)
    {   
        $this->post = $post;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {   
        $resized_image_path = storage_path('app/public/').rand(5, 100).'.jpg';
        $image = Image::make($post->org_path);
        $image->resize(200,200)->save($resized_image_path);
    }
}

I can't access in some way to the image from the job. Can you please tell me what I'm missing?


Solution

  • You should be accessing the post object using $this->post on the 2nd line of the handle() method and not $post that you have assigned on the constructor. Hopefully that fixes the issue.