Search code examples
laravelsms

How to send SMS 5 days before the date with Laravel?


After the Excel output, I want to send an SMS to the person's mobile number with the date entered in Excel 5 days before that date.

I also used the job command.

Controller.php

public function import(Request $request)
{
    Excel::import(new OtherImport, $request->file('file')->store('temp'));
    $insuranceData = Other::query()->select('personal_insurance', 'mobile')->get();

    $sentMobileNumbers = [];

    foreach ($insuranceData as $data) {
        $insuranceDate = $data->personal_insurance;
        $mobileNumber = $data->mobile;

        if (!empty($insuranceDate) && !in_array($mobileNumber, $sentMobileNumbers)) {
            try {
                $jalaliDate = Jalalian::fromFormat('Y/m/d', $insuranceDate);
                $carbonDate = Carbon::create($jalaliDate->getYear(), $jalaliDate->getMonth(), $jalaliDate->getDay());
                $smsDate = $carbonDate->subDay(5); 

                if ($smsDate->isPast()) {
                    SendSmsJob::dispatch([$mobileNumber]); 
                    $sentMobileNumbers[] = $mobileNumber; 
                }
            } catch (\Exception $e) {
                dd($e->getMessage());
            }
        }
    }
    return back();
} 

Solution

  • you need to use

    dispatch()->delay(now()->addDays(5));
    

    Bur remember that you need to do some changes

    1. Change QUEUE_CONNECTION=sync in your ENV file. You have to use a driver that allows you to use the queue, for example 'database'
    2. Then enable the queue worker with php artisan queue:work or supervisor if you're in production.