Martin Eckleben
Martin Eckleben

Reputation: 802

Laravel Backpack custom validation over multiple attributes

How do I custom validate multiple attributes in a Laravel Backpack CRUD controller update?

Lets say I have a ZIP, CITY, DELIVERY_PICKUP and DELIVERY_SHIPPING.
And lets say my wanted rules are:

  1. one of DELIVERY_PICKUP and/or DELIVERY_SHIPPING has to be selected
  2. if DELIVERY_SHIPPING is chosen ZIP and CITY need to be filled

Its possible to write custom validation rules with multiple attributes in laravel like this

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;
    }

But how do I fit it in Backpacks FormRequest and fill it with the values?

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',
        ];
    }

Upvotes: 0

Views: 1459

Answers (1)

xavidejuan
xavidejuan

Reputation: 433

I think that you can do it without a custom validation.

  1. To validate that one of delivery_pickup and/or delivery_shipping are selected you can use required_without validation:
'delivery_shipping' => 'required_without:delivery_pickup',
'delivery_pickup' => 'required_without:delivery_shipping',
  1. To validate zip and city you can use required_with valdiation:
'zip' => 'required_with:delivery_shipping',
'city' => 'required_with:delivery_shipping',

All together:

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

Upvotes: 1

Related Questions