Search code examples
laravelphp-carbonlaravel-mail

Laravel Date Difference with Carbon


I am trying to send email three days before the expired date, but I'm not sure how to?

Logic

  1. Retrieve all subscribers that are three days left to expire
  2. Send email to their users

Code

Table I need to check timestamps named subscribes.

$subscribes = Subscribe::all();

This table has a column named expires_at which I need to check this for finding 3 days left.

And my mailing

Mail::to($user->email)->send(new SubscribeExpire($user, $subscribe));

I'm confused with this Carbon calculation thing, anyone can help with that?

Update

based on answer below now I have this:

$subscribes = Subscribe::where('expires_at', Carbon::now()->subDays(3))->get();
        $user = [];
        $package = [];
        foreach($subscribes as $subscribe){
            $user = User::where('email', $subscribe->email);
            $package = Package::where('id', $subscribe->package_id);
        }

        Mail::to($user->email)->send(new SubscribeExpire($user, $package));

but when I run the command it get this error

ErrorException  : Trying to get property 'email' of non-object

Solution

  •   // here you get subscribes  
      // if you are going to send three days before the expiry date, this means we need to check if expires_at is in three days so probably need to add days. Or maybe even check if time left before expiration is more than three days and less than one day and run it once per day?
      $subscribes = Subscribe::whereDate('expires_at', Carbon::now()->addDays(3))->get();
        $user = [];
        $package = [];
        foreach($subscribes as $subscribe){
            // you probably have only one user with this email
            $user = User::where('email', $subscribe->email)->first();
            // you probably have one associated package
            $package = Package::where('id', $subscribe->package_id)->first();
        }
        // check if user and package are found
        if(is_object($user) && is_object($package)){
          Mail::to($user->email)->send(new SubscribeExpire($user, $package));
        }