doulong2782 2019-03-05 19:07
浏览 35

Laravel - 将代码移动到作业队列,而不是触发

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.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 yolov8边框坐标
    • ¥15 matlab中使用gurobi时报错
    • ¥15 WPF 大屏看板表格背景图片设置
    • ¥15 这个主板怎么能扩出一两个sata口
    • ¥15 不是,这到底错哪儿了😭
    • ¥15 2020长安杯与连接网探
    • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
    • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
    • ¥16 mybatis的代理对象无法通过@Autowired装填
    • ¥15 可见光定位matlab仿真