Reputation: 1353
i'm doing an ecommerce, i created:
-Session "cart" with all products attributes ( price, id, quantity, category etc)
-CouponController.php
namespace dixard\Http\Controllers;
use Illuminate\Http\Request;
use dixard\Http\Requests;
use dixard\Http\Controllers\Controller;
use dixard\Coupon;
use dixard\Http\Controllers\Carbon\Carbon;
class CouponController extends Controller
public function postCoupon(Request $request)
{
$cart = \Session::get('cart');
$mytime = Carbon\Carbon::now(); // today
// i check if code coupon exist into my DB
$coupon = Coupon::where('code', $request->get('coupon'))->first();
if (!empty($coupon) && $coupon->expire_date ) {
// i need check IF coupon exist AND date not expired --> i will put a new price into my session cart products.
}
}
Model Coupon.php
protected $table = 'coupons';
protected $fillable = [
'code', // code of coupon
'price', // price discount
'expire_date', // expire date of coupon
];
MY QUESTION
I would like:
How can i do this ?
Thank you for yout help! ( i read something about carbon, but i dont undestand fine)
Upvotes: 6
Views: 22957
Reputation: 109
$now = Carbon::now();
$startDate = Carbon::parse($yourModelObject['created_at'])->format('d.m.Y h:m:sa');
$endDate = Carbon::parse($yourModelObject['created_at'])->addMinutes(720)->format('d.m.Y h:m:sa');
if ($now->between($startDate, $endDate)) {
return 'Date is Active';
} else {
return 'Date is Expired';
}
Upvotes: 2
Reputation: 1616
Use date mutators in order to make expire_date
field a Carbon instance automatically.
class Coupon extends Model
{
/**
* The attributes that should be mutated to dates.
*
* @var array
*/
protected $dates = ['expire_date'];
}
So after that I think you only need to check if the expiring date of coupon is a future date.
if (!empty($coupon) && $coupon->expire_date->isFuture() ) {
// valid coupon
}
else{
return redirect()->back()->withErrors(['coupon' => 'Coupon is not valid']);
}
Upvotes: 9
Reputation: 3262
If $coupon->expire_date
is not instance of Carbon
already, make it (new Carbon($coupon->expire_date)
, then simply compare those two objects as if they were numbers.
For example (assuming that $coupon->expire_date
is instance of Carbon
:
if ($coupon->expire_date >= $my_time) {
// ok
} else {
// error, coupon expired
}
Carbon is very handy for all sorts of comparisons, calculating differences etc. Here you can find loads of examples.
Upvotes: 3