Your Essential Queries
How To Upload Bulk Data Using Laravel Queue
We'll See How To Upload Bulk Data Using Laravel Queue Easily:
1) Update .env file
- QUEUE_CONNECTION=database
2) Open Terminal
- cd /var/www/project__dir
3) Generate migrations for queue table
- php artisan queue:table
4) Migrate tables
- php artisan migrate
5) Create a job
- php artisan make:job BulkUserInsertJob
6) Edit app/Models/User.php file & disable guard
- protected $guarded = [];
7) Edit app/Jobs/BulkUserInsertJob.php file
- <?php
- namespace App\Jobs;
- use Illuminate\Bus\Queueable;
- use Illuminate\Contracts\Queue\ShouldBeUnique;
- use Illuminate\Contracts\Queue\ShouldQueue;
- use Illuminate\Foundation\Bus\Dispatchable;
- use Illuminate\Queue\InteractsWithQueue;
- use Illuminate\Queue\SerializesModels;
- use App\Models\User;
- class BulkUserInsertJob implements ShouldQueue
- {
- use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
- public $data;
- /**
- * Create a new job instance.
- *
- * @return void
- */
- public function __construct($data)
- {
- $this->data = $data;
- }
- /**
- * Execute the job.
- *
- * @return void
- */
- public function handle()
- {
- User::insert($this->data);
- }
- }
8) Create a controller
- php artisan make:controller UserUploadController
9) Edit app/Http/Controllers/UserUploadController.php file
- <?php
- namespace App\Http\Controllers;
- use Illuminate\Http\Request;
- use App\Jobs\BulkUploadJob;
- class UserUploadController extends Controller
- {
- public function upload()
- {
- $users = [
- [
- 'name' => 'User1',
- 'email' => 'user1@gmail.com'
- ],
- [
- 'name' => 'User2',
- 'email' => 'user2@gmail.com'
- ],
- [
- 'name' => 'User3',
- 'email' => 'user3@gmail.com'
- ],
- //....
- ];
- BulkUserInsertJob::dispatch($users);
- }
- }
10) Create a route inside routes/web.php
- Route::get('/upload-users', [\App\Http\Controllers\UserUploadController::class, 'upload']);
11) Run queue worker for listening
- php artisan queue:work
12) Visit http://localhost:8000/upload-users to insert bulk users through queue