Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.1 - Checking if the date expired

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:

  1. Check with my CouponController if the code coupon is expired or not
  2. If expired return a simply message "Coupon invalid"
  3. If Coupon code exist into my DB and NOT expired, i need create a new variable with price value of coupon , for example "$discount = Coupon->price", so i can pass my discount price to my checkout view.

How can i do this ?

Thank you for yout help! ( i read something about carbon, but i dont undestand fine)

like image 964
Diego Cespedes Avatar asked May 31 '16 09:05

Diego Cespedes


2 Answers

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']);
}
like image 128
Claudio King Avatar answered Sep 29 '22 06:09

Claudio King


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.

like image 27
Oliver Maksimovic Avatar answered Sep 29 '22 06:09

Oliver Maksimovic