在Laravel中使用会话和Eloquent ORM的购物车

301 阅读2分钟

创建数据库

创建名为laravel_db的新数据库。在这个数据库中,创建新的表,命名为产品,如下所示。

产品表的结构

(adsbygoogle = window.adsbygoogle || []).push({});

产品表的数据

安装Laravel

  1. getcomposer.org/download/下载并安装最新版本的Composer.

  2. Visual Studio Code中打开Windows终端,用下面的命令安装Laravel安装程序

    composer global require laravel/installer
    
  3. 创建新的文件夹,命名为LearnLaravelWithRealApps。使用Visual Studio Code打开LearnLaravelWithRealApps文件夹.在这个文件夹中,创建新的项目,名为LearnLaravelWithRealApps,命令如下。

    laravel new LearnLaravelWithRealApps
    

    (adsbygoogle = window.adsbygoogle || []).push({});

  4. 运行LearnLaravelWithRealApps项目,命令如下。

    php artisan serve
    
  5. 打开LearnLaravelWithRealApps项目,网址如下。

    http://localhost:8000
    

    (adsbygoogle = window.adsbygoogle || []).push({});

连接到数据库

打开根目录下的**.env**文件.添加如下值,连接到数据库。

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=laravel_db
DB_USERNAME=root
DB_PASSWORD=

清除配置缓存

Visual Studio Code中打开Windows终端,用下面的命令清除配置缓存。

php artisan config:clear

(adsbygoogle = window.adsbygoogle || []).push({})。

创建产品模型

app/Models文件夹下创建名为Product.php的新PHP文件,如下所示。

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $primarykey = 'id';
    protected $table = 'product';
    public $timestamps = false;
}

创建ProductRepository接口

创建名为Repositories的新文件夹。在Repositories文件夹中,创建名为Product的新文件夹。在app/Repositories/Product文件夹下创建名为ProductRepository.php的新PHP文件,如下所示。

<?php

namespace App\Repositories\Product;

interface ProductRepository
{
    public function findAll();

    public function find($id);
}

(adsbygoogle = window.adsbygoogle || []).push({})。

创建ProductRepositoryImpl类

app/Repositories/Product文件夹下创建名为ProductRepositoryImpl.php的新PHP文件,如下所示。

<?php

namespace App\Repositories\Product;

use App\Models\Product;

class ProductRepositoryImpl implements ProductRepository
{
    public function findAll()
    {
        return Product::get();
    }

    public function find($id)
    {
        return Product::find($id);
    }
}

声明产品仓库

打开app/Providers文件夹下的AppServiceProvider.php文件,添加声明新的资源库到注册方法,如下所示。

<?php

namespace App\Providers;

use App\Repositories\Product\ProductRepository;
use App\Repositories\Product\ProductRepositoryImpl;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->bind(ProductRepository::class, ProductRepositoryImpl::class);
    }

    public function boot()
    {
    }
}

(adsbygoogle = window.adsbygoogle || []).push({})。

控制员

app/Http/Controllers文件夹中,创建新的控制器,如下所示。

产品控制器

创建名为ProductController.php的新PHP文件,如下所示。

<?php

namespace App\Http\Controllers;

use App\Repositories\Product\ProductRepository;

class ProductController extends Controller
{
    protected $productRepository;

    public function __construct(ProductRepository $productRepository)
    {
        $this->productRepository = $productRepository;
    }

    public function index()
    {
        $data = [
            'products' => $this->productRepository->findAll()
        ];
        return view('product/index')->with($data);
    }
}

(adsbygoogle = window.adsbygoogle || []).push({})。

购物车控制器

创建新的PHP文件名为CartController.php,如下所示。

<?php

namespace App\Http\Controllers;

use App\Repositories\Product\ProductRepository;
use Illuminate\Http\Request;

class CartController extends Controller
{
    protected $productRepository;

    public function __construct(ProductRepository $productRepository)
    {
        $this->productRepository = $productRepository;
    }

    public function index(Request $request)
    {
        $data = [
            'cart' => $request->session()->get('cart')
        ];
        return view('cart/index')->with($data);
    }

    public function buy($id, Request $request)
    {
        if (!$request->session()->has('cart')) {
            $cart = array();
            array_push($cart, [
                'product' => $this->productRepository->find($id),
                'quantity' => 1
            ]);
            $request->session()->put('cart', $cart);
        } else {
            $cart = $request->session()->get('cart');
            $index = $this->exists($id, $cart);
            if ($index == -1) {
                array_push($cart, [
                    'product' => $this->productRepository->find($id),
                    'quantity' => 1
                ]);
            } else {
                $cart[$index]['quantity']++;
            }
            $request->session()->put('cart', $cart);
        }
        return redirect('cart');
    }

    public function remove($id, Request $request)
    {
        $cart = $request->session()->get('cart');
        $index = $this->exists($id, $cart);
        unset($cart[$index]);
        $request->session()->put('cart', array_values($cart));
        return redirect('cart');
    }

    public function update(Request $request)
    {
        $quantities = $request->input('quantity');
        $cart = $request->session()->get('cart');
        for ($i = 0; $i < count($cart); $i++) {
            $cart[$i]['quantity'] = $quantities[$i];
        }
        $request->session()->put('cart', $cart);
        return redirect('cart');
    }

    private function exists($id, $cart)
    {
        for ($i = 0; $i < count($cart); $i++) {
            if ($cart[$i]['product']->id == $id) {
                return $i;
            }
        }
        return -1;
    }
}

(addsbygoogle = window.addsbygoogle || []).push({})。

视图

resources/views文件夹中,创建新的视图,如下所示。

产品视图

resources/views文件夹中创建名为product的新文件夹。在这个文件夹中,创建名为index.blade.php的新Blade文件,如下所示。

<html>

    <head>
        <title>Laravel</title>
    </head>

    <body>

        <h3>Index</h3>
        <table border="1">
            <tr>
                <th>Id</th>
                <th>Name</th>
                <th>Price</th>
                <th>Quantity</th>
                <th>Status</th>
                <th>Created</th>
                <th>Description</th>
                <th>Action</th>
            </tr>
            @foreach($products as $product)
            <tr>
                <td>{{$product->id}}</td>
                <td>{{$product->name}}</td>
                <td>{{$product->price}}</td>
                <td>{{$product->quantity}}</td>
                <td>{{$product->status}}</td>
                <td>{{$product->created}}</td>
                <td>{{$product->description}}</td>
                <td>
                    <a href="{{url('/cart/buy/'.$product->id)}}">Buy Now</a>
                </td>
            </tr>
            @endforeach
        </table>

    </body>

</html>

(adsbygoogle = window.adsbygoogle || []).push({})。

购物车视图

resources/views文件夹中创建名为cart的新文件夹。在这个文件夹中,创建名为index.blade.php的新刀片文件,如下所示。

<html>

    <head>
        <title>Laravel</title>
    </head>

    <body>

        <a href="{{url('/product')}}">Continue Shopping</a>
        <h3>Cart</h3>
        <form method="post" action="{{url('/cart/update')}}">
            @csrf
            <table border="1">
                <tr>
                    <th>Action</th>
                    <th>Id</th>
                    <th>Name</th>
                    <th>Price</th>
                    <th>Quantity <input type="submit" value="Update"></th>
                    <th>Total</th>
                </tr>
                @php $total = 0; @endphp
                @foreach($cart as $item)
                @php $total += $item['product']->price * $item['quantity']; @endphp
                <tr>
                    <td align="center"><a href="{{url('/cart/remove/'.$item['product']->id)}}">X</a></td>
                    <td>{{$item['product']->id}}</td>
                    <td>{{$item['product']->name}}</td>
                    <td>{{$item['product']->price}}</td>
                    <td>
                        <input type="number" min="1" value="{{$item['quantity']}}" name="quantity[]" style="width: 70px">
                    </td>
                    <td>{{$item['product']->price * $item['quantity']}}</td>
                </tr>
                @endforeach
                <tr>
                    <td colspan="5" align="right">Total</td>
                    <td>{{$total}}</td>
                </tr>
            </table>
        </form>

    </body>

</html>

(adsbygoogle = window.adsbygoogle || []).push({})。

路由

打开routes文件夹中的web.php文件, 添加新的路由,如下所示:

<?php
    
use App\Http\Controllers\CartController;
use Illuminate\Support\Facades\Route;

use App\Http\Controllers\ProductController;

Route::group(['prefix' => 'product'], function () {
    Route::get('/', [ProductController::class, 'index']);
    Route::get('/index', [ProductController::class, 'index']);
});

Route::group(['prefix' => 'cart'], function () {
    Route::get('/', [CartController::class, 'index']);
    Route::get('/index', [CartController::class, 'index']);
    Route::get('/buy/{id}', [CartController::class, 'buy']);
    Route::get('/remove/{id}', [CartController::class, 'remove']);
    Route::post('/update', [CartController::class, 'update']);
});

Laravel项目的结构

(adsbygoogle = window.adsbygoogle || []).push({});

运行应用程序

Demo控制器中访问index动作, 网址如下:http://localhost:8000/product/index

输出

点击立即购买链接选择产品添加到购物车

输出

The postShopping Cart with Session and Eloquent ORM in Laravelappeared first onLearn Programming with Real Apps.