Users have plans stored in the invoices
table. These plans are monthly based.
What I need to do
I want to add a new row for user if his plan expire date has reached and they didn't renew their plans (I don't want to update old one)
The issue is
Each user has unlimited rows in invoices
table as they renew each month. Now when I try to retrieve their latest row and check the expiring date it gets other rows of those users as well.
Example
- My user has
3 rows
ininvoices
- two of them already expired and renewed, the current one is
id=3
- when I try to expire this
id=3
and createid=4
for this user - it gets all
3 rows
and send 3 emails to the user.
Code
public function handle()
{
$invoices = Invoice::where('plan_expire', '<=', Carbon::now())->get();
$current = Carbon::now();
$expiredatetime = $current->addDays(30);
$useType = Type::where('name', 'Free')->first();
foreach($invoices as $invoice)
{
Invoice::create([
'user_id' => $invoice->user->id,
'type_id' => $useType->id,
'amount' => $useType->price,
'status' => 'Approved',
'plan_expire' => $expiredatetime->toDateTimeString(),
]);
Mail::to($invoice->user->email)->send(new UserPlansReset($invoice));
}
}
User model
public function invoices()
{
return $this->hasMany(Invoice::class);
}
Invoice model
protected $fillable = [
'user_id', 'type_id', 'amount', 'status', 'plan_expire',
];
protected $casts = [
'plan_expire' => 'datetime',
];
public function user()
{
return $this->belongsTo(User::class);
}
Question
Do you have any idea how I can only get users latest row in invoices
table?
Update
based on answers below I changed my code to:
$current = Carbon::now();
$expiredatetime = $current->addDays(30);
$useType = Type::where('name', 'Free')->first();
$users = User::all();
foreach($users as $user){
$latestInvoice = $user->invoices()->latest()->first();
if(!empty($latestInvoice) && $latestInvoice->plan_expire <= Carbon::now()){
Invoice::create([
'user_id' => $user->id,
'type_id' => $useType->id,
'amount' => $useType->price,
'status' => 'Approved',
'plan_expire' => $expiredatetime->toDateTimeString(),
]);
Mail::to($user->email)->send(new UserPlansReset($user));
}
}
Now this function will return
Expected response code 220 but got an empty response
and wont send emails.