When working with queued jobs in Laravel, including queued exports with the maatwebsite/laravel-nova-excel package, you need to be aware that the request object, including the authenticated user, is not automatically serialized and passed to the job. This is because the request object is tied to the current HTTP request and is not available in the background job.
To solve this issue, you can manually pass the user information to the queued export job. Here’s how you can do it:
-
Create a Custom Export Class: Extend the
QueuedExportclass and add a constructor to accept the user. -
Pass the User to the Export Class: When dispatching the export job, pass the authenticated user to the export class.
-
Use the User in the Export Class: Use the passed user information within the export class.
Here’s an example implementation:
Step 1: Create a Custom Export Class
Create a custom export class that extends QueuedExport and accepts the user in the constructor.
namespace App\Exports;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\ShouldQueue;
use Illuminate\Contracts\Queue\ShouldQueue as ShouldQueueContract;
class CustomExport implements FromCollection, WithHeadings, ShouldQueue
{
protected $user;
public function __construct($user)
{
$this->user = $user;
}
public function collection()
{
// Use $this->user to filter or customize the data
return collect([
// Your data here
]);
}
public function headings(): array
{
return [
'Heading 1',
'Heading 2',
// Your headings here
];
}
}
Step 2: Dispatch the Export Job with the User
When you dispatch the export job, pass the authenticated user to the export class.
use App\Exports\CustomExport;
use Maatwebsite\Excel\Facades\Excel;
public function export()
{
$user = request()->user();
return Excel::queue(new CustomExport($user), 'export.xlsx');
}
Step 3: Use the User in the Export Class
Within your CustomExport class, you can now use the $this->user property to access the authenticated user and customize the export data accordingly.
This approach ensures that the user information is properly serialized and available within the queued job, avoiding the Call to a member function funcName() on null exception.
By following these steps, you should be able to pass the authenticated user to your queued export job in Laravel Nova Excel.