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)
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']);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With