Laravel 8 Add To Cart Function With Ajax Example
Hello Dev,
Immediately, i we’ll present you laravel Eight add to cart perform with ajax instance. This text will provide you with easy instance of laravel Eight add to cart perform with ajax instance. you’ll study laravel Eight add to cart perform with ajax instance.
On this artical i’ll present you the right way to create add to cart performance in laravel 8. After we make a ecommerce web site, we’d like the add to cart perform. We are able to use this instance in Laravel 6, Laravel 7, Laravel 8, all. So let’s comply with few step to create instance of laravel Eight add to cart perform with ajax instance.
Preview:
Step 1:- Set up Laravel
First of, open your terminal and set up new Laravel:
composer create-project --prefer-dist laravel/laravel addtocart
Step 2:- Join Database .env
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=databse DB_USERNAME=root DB_PASSWORD=
Step 3:- Create Desk, Mannequin and Seeder
On this step, we have to create product desk, mannequin and add some dummy knowledge with seeder
Create Migration
php artisan make:migration create_products_table
Migration
<?php use IlluminateDatabaseMigrationsMigration; use IlluminateDatabaseSchemaBlueprint; use IlluminateSupportFacadesSchema; class CreateProductsTable extends Migration { /** * Run the migrations. * * @return void */ public perform up() { Schema::create('merchandise', perform (Blueprint $desk) { $table->id(); $table->string("identify", 255)->nullable(); $table->textual content("description")->nullable(); $table->string("picture", 255)->nullable(); $table->decimal("value", 6, 2); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public perform down() { Schema::dropIfExists('merchandise'); } }
migration now:-
php artisan migrate
Create Mannequin
php artisan make:mannequin Product
app/Fashions/Product.php
<?php namespace AppModels; use IlluminateDatabaseEloquentFactoriesHasFactory; use IlluminateDatabaseEloquentModel; class Product extends Mannequin { use HasFactory; protected $fillable = [ 'name', 'price', 'description', 'image' ]; }
Create Seeder
run command to create Product seeder:
php artisan make:seed ProductSeeder
database/seeders/ProductSeeder.php
<?php namespace DatabaseSeeders; use IlluminateDatabaseSeeder; use AppModelsProduct; class ProductSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public perform run() { $merchandise = [ [ 'name' => 'Samsung Galaxy', 'description' => 'Samsung Brand', 'image' => 'https://codeplaners.com/wp-content/uploads/2020/09/cropped-favicon-social-192x192.png', 'price' => 100 ], [ 'name' => 'Apple iPhone 12', 'description' => 'Apple Brand', 'image' => 'https://codeplaners.com/wp-content/uploads/2020/09/cropped-favicon-social-192x192.png', 'price' => 500 ], [ 'name' => 'Google Pixel 2 XL', 'description' => 'Google Pixel Brand', 'image' => 'https://codeplaners.com/wp-content/uploads/2020/09/cropped-favicon-social-192x192.png, 'price' => 400 ], [ 'name' => 'LG V10 H800', 'description' => 'LG Brand', 'image' => 'https:'https://codeplaners.com/wp-content/uploads/2020/09/cropped-favicon-social-192x192.png', 'price' => 200 ] ]; foreach ($merchandise as $key => $worth) { Product::create($worth); } } }
Run seeder:
php artisan db:seed --class=ProductSeeder
Step 4:- Create Route
routes/net.php
<?php use IlluminateSupportFacadesRoute; use AppHttpControllersProductController; /* |-------------------------------------------------------------------------- | Internet Routes |-------------------------------------------------------------------------- | | Right here is the place you possibly can register net routes in your utility. These | routes are loaded by the RouteServiceProvider inside a gaggle which | incorporates the "net" middleware group. Now create one thing nice! | */ //Route::get('/', perform () { // return view('welcome'); //}); Route::get('/', [ProductController::class, 'index']); Route::get('cart', [ProductController::class, 'cart'])->identify('cart'); Route::get('add-to-cart/{id}', [ProductController::class, 'addToCart'])->identify('add.to.cart'); Route::patch('update-cart', [ProductController::class, 'update'])->identify('replace.cart'); Route::delete('remove-from-cart', [ProductController::class, 'remove'])->identify('take away.from.cart');
Step 5:- Add Controller
app/Http/Controllers/ProductController.php
<?php namespace AppHttpControllers; use IlluminateHttpRequest; use AppModelsProduct; class ProductController extends Controller { /** * Write code on Technique * * @return response() */ public perform index() { $merchandise = Product::all(); return view('merchandise', compact('merchandise')); } /** * Write code on Technique * * @return response() */ public perform cart() { return view('cart'); } /** * Write code on Technique * * @return response() */ public perform addToCart($id) { $product = Product::findOrFail($id); $cart = session()->get('cart', []); if(isset($cart[$id])) { $cart[$id]['quantity']++; } else { $cart[$id] = [ "name" => $product->name, "quantity" => 1, "price" => $product->price, "image" => $product->image ]; } session()->put('cart', $cart); return redirect()->again()->with('success', 'Product added to cart efficiently!'); } /** * Write code on Technique * * @return response() */ public perform replace(Request $request) { if($request->id && $request->amount){ $cart = session()->get('cart'); $cart[$request->id]["quantity"] = $request->amount; session()->put('cart', $cart); session()->flash('success', 'Cart up to date efficiently'); } } /** * Write code on Technique * * @return response() */ public perform take away(Request $request) { if($request->id) { $cart = session()->get('cart'); if(isset($cart[$request->id])) { unset($cart[$request->id]); session()->put('cart', $cart); } session()->flash('success', 'Product eliminated efficiently'); } } }
Step 6:- Add Blade Information
we have to add blade recordsdata for structure, merchandise and cart web page.
assets/views/structure.blade.php
<!DOCTYPE html> <html> <head> <title>Laravel Eight Add To Cart Perform With Ajax Instance - codeplaners.com</title> <hyperlink rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"> <hyperlink rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script> <hyperlink href="{{ asset('css/model.css') }}" rel="stylesheet"> </head> <physique> <div class="container"> <div class="row"> <div class="col-lg-12 col-sm-12 col-12 main-section"> <nav class="navbar"> <ul> <li><a category="nav-link" href="/">Dwelling</a></li> <li><a category="nav-link" href="#">About Us</a></li> </ul> <div class="dropdown"> <button kind="button" class="btn btn-info" data-toggle="dropdown"> <i class="fa fa-shopping-cart" aria-hidden="true"></i> Cart <span class="badge badge-pill badge-danger">{{ depend((array) session('cart')) }}</span> </button> <div class="dropdown-menu"> <div class="row total-header-section"> <div class="col-lg-6 col-sm-6 col-6"> <i class="fa fa-shopping-cart" aria-hidden="true"></i> <span class="badge badge-pill badge-danger">{{ depend((array) session('cart')) }}</span> </div> @php $whole = 0 @endphp @foreach((array) session('cart') as $id => $particulars) @php $whole += $particulars['price'] * $particulars['quantity'] @endphp @endforeach <div class="col-lg-6 col-sm-6 col-6 total-section text-right"> <p>Complete: <span class="text-info">$ {{ $whole }}</span></p> </div> </div> @if(session('cart')) @foreach(session('cart') as $id => $particulars) <div class="row cart-detail"> <div class="col-lg-Four col-sm-Four col-Four cart-detail-img"> <img src="{{ $particulars['image'] }}" /> </div> <div class="col-lg-Eight col-sm-Eight col-Eight cart-detail-product"> <p>{{ $particulars['name'] }}</p> <span class="value text-info"> ${{ $particulars['price'] }}</span> <span class="depend"> Amount:{{ $particulars['quantity'] }}</span> </div> </div> @endforeach @endif <div class="row"> <div class="col-lg-12 col-sm-12 col-12 text-center checkout"> <a href="{{ route('cart') }}" class="btn btn-primary btn-block">View all</a> </div> </div> </div> </div> </nav> </div> </div> </div> <br/> <div class="container"> @if(session('success')) <div class="alert alert-success"> {{ session('success') }} </div> @endif @yield('content material') </div> @yield('scripts') </physique> </html>
assets/views/merchandise.blade.php
@extends('structure') @part('content material') <div class="row"> @foreach($merchandise as $product) <div class="col-xs-18 col-sm-6 col-md-3"> <div class="product_box"> <img src="{{ $product->picture }}" alt=""> <div class="caption"> <h4>{{ $product->identify }}</h4> <p>{{ $product->description }}</p> <p><sturdy>Value: </sturdy> {{ $product->value }}$</p> <p class="btn-holder"><a href="{{ route('add.to.cart', $product->id) }}" class="btn btn-warning btn-block text-center" function="button">Add to cart</a> </p> </div> </div> </div> @endforeach </div> @endsection
assets/views/cart.blade.php
@extends('structure') @part('content material') <desk id="cart" class="desk table-hover table-condensed"> <thead> <tr> <th model="width:50%">Product</th> <th model="width:10%">Value</th> <th model="width:8%">Amount</th> <th model="width:22%" class="text-center">Subtotal</th> <th model="width:10%"></th> </tr> </thead> <tbody> @php $whole = 0 @endphp @if(session('cart')) @foreach(session('cart') as $id => $particulars) @php $whole += $particulars['price'] * $particulars['quantity'] @endphp <tr data-id="{{ $id }}"> <td data-th="Product"> <div class="row"> <div class="col-sm-Three hidden-xs"><img src="{{ $particulars['image'] }}" width="100" top="100" class="img-responsive"/></div> <div class="col-sm-9"> <h4 class="nomargin">{{ $particulars['name'] }}</h4> </div> </div> </td> <td data-th="Value">${{ $particulars['price'] }}</td> <td data-th="Amount"> <enter kind="quantity" worth="{{ $particulars['quantity'] }}" class="form-control amount update-cart" /> </td> <td data-th="Subtotal" class="text-center">${{ $particulars['price'] * $particulars['quantity'] }}</td> <td class="actions" data-th=""> <button class="btn btn-danger btn-sm remove-from-cart"><i class="fa fa-trash-o"></i></button> </td> </tr> @endforeach @endif </tbody> <tfoot> <tr> <td colspan="5" class="text-right"><h3><sturdy>Complete ${{ $whole }}</sturdy></h3></td> </tr> <tr> <td colspan="5" class="text-right"> <a href="{{ url('/') }}" class="btn btn-warning"><i class="fa fa-angle-left"></i> Proceed Procuring</a> <button class="btn btn-success">Checkout</button> </td> </tr> </tfoot> </desk> @endsection @part('scripts') <script kind="textual content/javascript"> $(".update-cart").change(perform (e) { e.preventDefault(); var ele = $(this); $.ajax({ url: '{{ route('replace.cart') }}', technique: "patch", knowledge: { _token: '{{ csrf_token() }}', id: ele.mother and father("tr").attr("data-id"), amount: ele.mother and father("tr").discover(".amount").val() }, success: perform (response) { window.location.reload(); } }); }); $(".remove-from-cart").click on(perform (e) { e.preventDefault(); var ele = $(this); if(affirm("Are you certain wish to take away?")) { $.ajax({ url: '{{ route('take away.from.cart') }}', technique: "DELETE", knowledge: { _token: '{{ csrf_token() }}', id: ele.mother and father("tr").attr("data-id") }, success: perform (response) { window.location.reload(); } }); } }); </script> @endsection
public/css/model.css
.navbar ul { padding: 0; list-style: none; show: flex; margin: 0; } .product_box { place: relative; padding: 10px; margin-bottom: 20px; box-shadow: Zero 0px 8px #ccc; text-align: heart; } .product_box .caption p { margin: 0; } .product_box .caption p a { background: #FF9800; shade: #fff; } button.btn.btn-info { background: #FF9800; } .text-info { shade: #FF9800 !vital; } .product_box img { width: 80%; } .product_box .caption{ margin: 7px; } .main-section{ background-color: #F8F8F8; } .dropdown{ float:proper; padding-right: 30px; } .btn{ border:0px; margin:10px 0px; box-shadow:none !vital; } .dropdown .dropdown-menu { padding: 20px; prime: 60px !vital; width: 350px !vital; left: -230px !vital; box-shadow: 0px 5px 30px black; } .total-header-section{ border-bottom:1px strong #d2d2d2; } .total-section p{ margin-bottom:20px; } .cart-detail{ padding:15px 0px; } .cart-detail-img img{ width:100%; top:100%; padding-left:15px; } .cart-detail-product p{ margin:0px; shade:#000; font-weight:500; } .cart-detail .value{ font-size:12px; margin-right:10px; font-weight:500; } .cart-detail .depend{ shade:#C2C2DC; } .checkout{ border-top:1px strong #d2d2d2; padding-top: 15px; } .checkout .btn-primary { border-radius: 50px; top: 45px; background: #FF9800; font-size: 22px; padding: 3px Zero 0; } .dropdown-menu:earlier than{ content material: " "; place:absolute; prime:-20px; proper:50px; border:10px strong clear; border-bottom-color:#fff; }
we’re able to run our instance
php artisan serve
Komentar
Posting Komentar