Queue task making request to access file from Laravel
P粉762447363
2023-09-03 13:43:56
<p>Hi everyone, I have a queued Laravel job to insert some records into the database via a file imported by the user. But whenever I access the request object in the job to get the uploaded file, I get null. However, the file is received normally in the controller. Any ideas? </p>
<p>Find the import method in the controller as follows: </p>
<pre class="brush:php;toolbar:false;">public function import(ImportPointRequest $request)
{
Storage::makeDirectory('import_logs');
$file = request()->file('file');
$fileName = 'importlog_date_' . date('Y-m-d') . '-user_' . auth()->id() . '.xlsx';
$logFile = 'import_logs/' . $fileName;
$readerTypes = ['xlsx' => Excel::XLSX, 'xls' => Excel::XLS, 'csv' => Excel::CSV];
$link = route('file.show', ['import_logs', $fileName]);
try {
ExcelFacade::import(new PointsImportHeading(), $file);
} catch (\Exception $e) {
return $this->returnBadRequest(config('point.error-codes.import-fail'), $e->getMessage());
}
(new PointsImport(auth()->user(), auth()->user()->account_id, $logFile))->queue(
$file->getRealPath(),
null,
$readerTypes[request()->file('file')->getClientOriginalExtension()]
)->chain([new AfterImportJob(auth()->id(), $logFile, $link)]);
return $this->returnSuccess(trans('point::point.import-queued', ['module' => trans('point::point.point')]));
}</pre>
<p>Find the getImportedFileContent method in the job as follows: </p>
<pre class="brush:php;toolbar:false;">protected function getUploadedFileContent(): array
{
return Excel::toArray(new PointsImportHeading(), request()->file('file'));
}</pre>
<p>The problem is that this part <code>request()->file('file')</code> always returns null. </p>
Your method is incorrect. In Laravel, the lifecycle of a request begins when the request arrives at the server and ends when the response is sent back to the user's browser. When you queue a job in Laravel, it means that the job will be processed later, maybe even on a different server. When the job actually runs, the original request life cycle has ended. Therefore, you cannot access request data within a queued job.
If you need to use the uploaded file in a queued job, you need to store the uploaded file in a location that the job can access. This can be your server's file system or a cloud storage service.
In your controller you have temporarily stored the file for processing with Excel:
However, you do not persist the file, which is why the file is not available while the job is running. You need to store your files somewhere more permanent.
After storing the file permanently, you can read the file from the new location.