1 year ago
#376480

Muhammad Shahzaib
Apply Coupon on products by Tag in Laravel
I've implemented coupons in my app. Coupon is applying on subtotal of all products in the cart. I want to apply the coupon on specific tag's products. There is many-to-many relationship between products and tags. The same tag I'll add while adding a new coupon, and coupon should apply on all the products in this specified tag.
Coupon Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Tag;
class Coupon extends Model
{
public static function findByCode($code) {
return self::where('code', $code)->first();
}
public function discount($total) {
if($this->type == 'fixed') {
return $this->value;
} else if($this->type == 'percent_off') {
return ($this->percent_off / 100) * $total;
} else {
return 0;
}
}
}
Coupons Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Coupon;
use Cart;
class CouponsController extends Controller
{
public function store(Request $request)
{
$this->validate($request, [
'coupon_code' => 'required'
]);
$coupon = Coupon::where('code', $request->coupon_code)->first();
$carts = collect([Cart::instance('product')->subtotal(), Cart::instance('specials')->subtotal()])->sum();
if(!$coupon)
return redirect()->back()->with('error', 'Invalid Coupon Code');
session()->put('coupon', [
'code' => $coupon->code,
'discount' => $coupon->discount($carts)
]);
return redirect()->back()->with('primary' ,'Coupon applied successfully!');
}
public function destroy()
{
session()->forget('coupon');
return redirect()->back()->with('warning', 'Coupon has been removed');
}
}
I will select the tag from admin panel when I'll add new coupon and it should apply on that tag's products.
php
laravel
controller
many-to-many
coupon
0 Answers
Your Answer