how to stop queue job after finish its execution automatically in Laravel?

I use queue job after (a user) registered, it sent an email for verifying, I set a delay (10 second) to run the job.

but the issue is that:

  • the queue job runs and executes the verifying email fine, but it still running in the background forever, and this consumes the resources:

enter image description here

how to stop it automatically after the execution of the job?

Route:

    Route::group(['middleware'=>'guest:web'], function(){
    Route::get('/register', [registerController::class,'register'])->name('site.register');
    Route::match(['get','post'],'/register-create', [registerController::class,'create'])->name('site.register.create');
});

Controller:

    public function create(RegisterRequest $request)
{
     $user = User::create([
        'firstName' => $request->firstName,
        'middleName' => $request->middleName,
        'lastName' => $request->lastName,
        'email' => $request->email,
        'password' => Hash::make($request->password),
    ]);
    $on = \Carbon\Carbon::now()->addSecond(10);
     dispatch(new VerifyEmailJob($user))->delay($on);
    return redirect()->route('landingPage')->with(['success'=>'We sent verifying email check it']);
}

queue job:

    <?php

namespace App\Jobs;

use App\Mail\VerifyEmail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Mail;

class VerifyEmailJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public $user;
    public function __construct($user)
    {
        $this->user= $user;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        Mail::to($this->user->email)->send(new VerifyEmail($this->user));

    }
}

Mail class:

    <?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class VerifyEmail extends Mailable
{
    use Queueable, SerializesModels;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public $user;

    public function __construct($user)
    {
        $this->user = $user;
    }
    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        $user = $this->user;
        return $this->subject('Mail from Oneme')
            ->view('site.auth.verifyEmail',compact('user'));
    }
}

Any Help please


Solution 1:

according to the Laravel documentation you have many options to handle the processing of you queue. I think you can use this one: https://laravel.com/docs/8.x/queues#processing-all-queued-jobs-then-exiting