Php 如何调用Laravel中的服务类?

Php 如何调用Laravel中的服务类?,php,laravel,Php,Laravel,我有一段代码需要用三种不同的方式编写,所以我决定为它制作服务类,并在我的三个控制器中对它进行分类!我谨此陈辞: 在Services文件夹中创建新文件调用CheckQuantity: <?php namespace App\Services; use App\Models\Product; class CheckQuantity { public function __construct($id) { $product = Product::findOr

我有一段代码需要用三种不同的方式编写,所以我决定为它制作
服务类
,并在我的三个控制器中对它进行分类!我谨此陈辞:

Services
文件夹中创建新文件调用
CheckQuantity

<?php

namespace App\Services;

use App\Models\Product;

class CheckQuantity
{
    public function __construct($id)
    {
        $product = Product::findOrFail($id);

        if(!is_null($product->quantity)){
            if($request->quantity > $product->quantity){
                return redirect()->back()->with('error','(trans('site.larger_than_qty_in_store'));
            }
        }
    }
}

现在,当我更新消息返回的数量,然后更新shuoldnot update的数量(只是重定向)

这不会解释404错误,但它可能更适合您的原始用例

为什么不在
产品
模型中添加一种方法呢

产品::类别

public function hasQuantity(int $quantity)
{
    return $this->quantity ? $this->quantity <= $quantity : false;
}

这消除了对服务类的需要,并允许您在有
产品
对象的地方重复使用您的检查

您到底在哪里得到404错误?显示错误。@当我提交编辑时,如果我只是删除服务类,其他代码就可以工作了!请再次显示错误。复制错误文本并更新您的问题以包含它。您得到了404,因为您使用了
Order$Order,Product$Product
,在这种情况下
$Order
$Product
应该是pass并且需要有效的,我认为您不需要
Product
,那么它将是
公共函数编辑(Order$Order,Request$Request)
@sta I更新代码!我现在对我的新代码有另一个问题,它可以工作,但数量正在更新,即使在_构造中有重定向!
public function hasQuantity(int $quantity)
{
    return $this->quantity ? $this->quantity <= $quantity : false;
}
public function edit(Order $order,Product $product,Request $request)
{
    // Check the product has the required quantity
    if (!$product->hasQuantity($request->quantity)) {
        return redirect()->back();
    }

    $order->products()->updateExistingPivot($product->id, [
        'quantity' => $request->quantity,
    ]);

    return redirect()->back()
            ->with('success',trans('site.quantity_updated'));
}