Level 73
@mehrdad70 you need to switch these lines:
$cart->courses()->attach($request->course_id);
$cart->save();
You cannot add course to a cart that does not exists yet.
$cart->save();
$cart->courses()->attach($request->course_id);
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I want to add the product to the cart but it gives an error
class Cart extends Model
{
protected $guarded = [];
public function courses()
{
return $this->belongsToMany(Course::class, 'cart_course' , 'cart_id' , 'course_id');
}
public function user()
{
return $this->belongsToMany(User::class);
}
}
Schema::create('carts', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained('users')->cascadeOnDelete();
$table->integer('total_amount');
// $table->boolean('is_used_discount')->default(0);
$table->integer('price');
// $table->bigInteger('discount_percent');
$table->bigInteger('total_discount');
$table->dateTime('expired_at');
$table->timestamps();
});
Schema::create('cart_course', function (Blueprint $table) {
$table->foreignId('cart_id')->constrained('carts')->cascadeOnDelete();
$table->foreignId('course_id')->constrained('courses')->cascadeOnDelete();
});
<form action="{{route('single-add-to-cart')}}" method="post">
@csrf
<input type="hidden" name="course_id" value="{{$course->id}}" id="">
<button type="submit" class="btn btn-info w-full">Add To Cart</button>
</form>
Route::get('/cart/{course}' , 'CartController@addToCart')->name('add-to-cart');
Route::post('/cart' , 'CartController@singeCart')->name('single-add-to-cart');
public function addToCart(Course $course ,Request $request)
{
$course = Course::where('id' , $request->course_id)->first();
if(empty($this->course_id)){
Alert::error('خطا' , 'هیچ محصولی در سبد خرید شما وجود ندارد' , 'error');
}
$activeCart = Cart::where('user_id' , auth()->id())->first();
if($activeCart){
$activeCart->total_amount = $course->price + $activeCart->total_amount;
$activeCart->save();
}
$cart = new Cart();
$cart->user_id = auth()->user()->id;
$cart->price = $course->price;
$cart->total_discount = 3000;
$cart->total_amount = $cart->price + $course->price;
$cart->courses()->attach($request->course_id);
$cart->save();
Alert::success('موفقیت آمیز' , 'محصول با موفقیت به سبد خرید شما اضافه شد' , 'success');
}
Please or to participate in this conversation.