KenoKivabe

Your Essential Queries

Author
Md Mojahedul Islam
30 Aug, 2022

How To Upload Bulk Data Using Laravel Queue

We'll See How To Upload Bulk Data Using Laravel Queue Easily:

1) Update .env file

  1. QUEUE_CONNECTION=database 

2) Open Terminal

  1. cd /var/www/project__dir

3) Generate migrations for queue table

  1. php artisan queue:table

4) Migrate tables

  1. php artisan migrate  

5) Create a job

  1. php artisan make:job BulkUserInsertJob  

6) Edit app/Models/User.php file & disable guard

  1. protected $guarded = []; 

7) Edit app/Jobs/BulkUserInsertJob.php file

  1. <?php  
  2.   
  3. namespace App\Jobs;  
  4.   
  5. use Illuminate\Bus\Queueable;  
  6. use Illuminate\Contracts\Queue\ShouldBeUnique;  
  7. use Illuminate\Contracts\Queue\ShouldQueue;  
  8. use Illuminate\Foundation\Bus\Dispatchable;  
  9. use Illuminate\Queue\InteractsWithQueue;  
  10. use Illuminate\Queue\SerializesModels;  
  11.   
  12. use App\Models\User;  
  13.   
  14. class BulkUserInsertJob implements ShouldQueue  
  15. {  
  16.     use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;  
  17.   
  18.     public $data;  
  19.     /** 
  20.      * Create a new job instance. 
  21.      * 
  22.      * @return void 
  23.      */  
  24.   
  25.     public function __construct($data)  
  26.     {  
  27.         $this->data = $data;  
  28.     }  
  29.   
  30.     /** 
  31.      * Execute the job. 
  32.      * 
  33.      * @return void 
  34.      */  
  35.     public function handle()  
  36.     {  
  37.         User::insert($this->data);  
  38.     }  
  39. }

8) Create a controller

  1. php artisan make:controller UserUploadController 

9) Edit app/Http/Controllers/UserUploadController.php file

  1. <?php  
  2.   
  3. namespace App\Http\Controllers;  
  4.   
  5. use Illuminate\Http\Request;  
  6.   
  7. use App\Jobs\BulkUploadJob;  
  8.   
  9. class UserUploadController extends Controller  
  10. {  
  11.     public function upload()  
  12.     {  
  13.         $users = [  
  14.             [  
  15.                 'name' => 'User1',  
  16.                 'email' => 'user1@gmail.com'  
  17.             ],  
  18.             [  
  19.                 'name' => 'User2',  
  20.                 'email' => 'user2@gmail.com'  
  21.             ],  
  22.             [  
  23.                 'name' => 'User3',  
  24.                 'email' => 'user3@gmail.com'  
  25.             ],  
  26.             //....  
  27.         ];  
  28.   
  29.         BulkUserInsertJob::dispatch($users);  
  30.     }  

10) Create a route inside routes/web.php

  1. Route::get('/upload-users', [\App\Http\Controllers\UserUploadController::class'upload']); 

11) Run queue worker for listening

  1. php artisan queue:work 

12) Visit http://localhost:8000/upload-users to insert bulk users through queue

Share: