Hello everyone I have a queued
Laravel job
that runs to insert some records in the database for an imported file by a user
. but whenever I access the request object to get the uploaded file
from inside the job
I got null
. however, the file is received
in the controller
normally. any idea?
find the import method below in the controller
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')]));
}
find the getImportedFileContent method below in the job
protected function getUploadedFileContent(): array
{
return Excel::toArray(new PointsImportHeading(), request()->file('file'));
}
The problem in this part request()->file('file')
always returns null.
Your approach is not true. In Laravel, the request lifecycle is started when a request comes to your server and it ends as soon as a response is sent back to the user's browser. When you queue a job in Laravel, it means that job will be processed later, perhaps even on a different server. When the job actually runs, the original request lifecycle is already over. Therefore, you cannot access the request data inside your queued job.
If you need to use the uploaded file in your queued job, you'll need to store the uploaded file in a location where your job can access it. This could be on your server's file system or on a cloud storage service.
In your controller, you're already storing the file temporarily to process it with Excel:
$file = request()->file('file');
However, you don't persist the file, which is why the file is not available when the job runs. You need to store the file somewhere more permanently.
After store your file permanently you can read the file from the new location.