I allow my users to upload images to a specific model (Stream
). I would like to move this code logic to a queue, so I can make the upload process a bit more smooth.
This is my StreamDocumentsController.php
, specifically the store method:
public function store(Stream $stream)
{
//Validate the request.
//Removed in this example.
//Store the actual document on the server.
$store = request()->file('file')->store($stream->token);
//Set the attributes to save to DB.
$attributes['name'] = request()->file->getClientOriginalName();
$attributes['path'] = $store;
dispatch(new UploadDocuments($stream, $attributes));
//Return URL for now. (JSON later on..)
return response()->json([
'status' => 'success'
]);
}
So above will actually store the image to the server, on this line:
//Store the actual document on the server.
$store = request()->file('file')->store($stream->token);
Now, when I try to run this code (upload an image), I can see in Laravel Horizon
that a job is indeed added, but the document is never added to the database.
This is my UploadDocuments
job:
protected $stream;
protected $attributes;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct(Stream $stream, $attributes)
{
$this->stream = $stream;
$this->attributes = $attributes;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$this->stream->addDocuments($this->attributes);
}
As you can see, I want my job to run the addDocuments()
method.
The actual method for this, is stored in my Stream
model:
Stream.php
:
/**
* A stream can have many documents
*/
public function documents()
{
return $this->hasMany(Document::class);
}
/**
* Add document(s) to the stream
*
* @return Illuminate\Database\Eloquent\Model
*/
public function addDocuments(array $attributes)
{
return $this->documents()->create($attributes);
}
So basically, when uploading the image the uploading process should be queued, but the above code only saves the actual image to the server, but never the database. It's like the handle()
method is never being fired.
Furthermore, is above correct? Because I don't handle the ->store($stream->token)
in my job, so this is never queued.
Any help would be greatly appreciated, as I am a bit lost.