Laravel 背包自定义验证多个属性

Laravel Backpack custom validation over multiple attributes

如何自定义验证 Laravel Backpack CRUD 控制器更新中的多个属性?

假设我有一个 ZIP、CITY、DELIVERY_PICKUP 和 DELIVERY_SHIPPING。
假设我想要的规则是:

  1. 必须选择 DELIVERY_PICKUP and/or DELIVERY_SHIPPING 之一
  2. 如果选择DELIVERY_SHIPPING需要填写ZIP和CITY

可以像这样在 laravel 中编写具有多个属性的自定义验证规则

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class Delivery implements Rule
{

    public $delivery_shipping;
    public $delivery_pick_up;
    public $zip;
    public $city;

    public function __construct($delivery_shipping,$delivery_pick_up,$zip,$city)
    {
        $this->delivery_shipping = $delivery_shipping;
        $this->delivery_pick_up = $delivery_pick_up;
        $this->zip = $zip;
        $this->city = $city;
    }

但是我如何将它放入 Backpacks FormRequest 中并用值填充它?

namespace App\Http\Requests;

use App\Http\Requests\Request;
use Illuminate\Foundation\Http\FormRequest;

class AdvertRequest extends FormRequest
{

    public function rules()
    {
        return [
            'title' => 'required|min:5|max:255',
            'frontend_user_id' => 'required',
            'profile_type' => 'required',
            'advertisement_type' => 'required',
            'marketplace_category_id' => 'required',
            'price' => 'numeric|nullable',
            'price_mode' => 'required',
            'content' => 'required',
            'zip' => 'required|numeric',
            'city' => 'required|min:1|max:255',
            'delivery_shipping' => 'Delivery',
        ];
    }

我认为你可以在没有自定义验证的情况下做到这一点。

  1. 要验证是否选择了 delivery_pickup and/or delivery_shipping,您可以使用 required_without 验证:
'delivery_shipping' => 'required_without:delivery_pickup',
'delivery_pickup' => 'required_without:delivery_shipping',
  1. 要验证邮政编码和城市,您可以使用 required_with 验证:
'zip' => 'required_with:delivery_shipping',
'city' => 'required_with:delivery_shipping',

总计:

rules = [
    'delivery_shipping' => 'required_without:delivery_pickup',
    'delivery_pickup' => 'required_without:delivery_shipping',
    'zip' => 'required_with:delivery_shipping',
    'city' => 'required_with:delivery_shipping',
];