基于 pivot table laravel 的唯一名称规则验证

unique name rule validation based on pivot table laravel

我有一个租车公司有车的系统。许多租车公司都可以提供汽车。所以是多对多的关系。

我想为公司提供在购买新车时添加新车的可能性。如果汽车已经存在,系统将不会创建它,但会显示一条错误消息,说明他们已经拥有那辆车。

如何在添加的Car名称字段使用唯一验证规则?挑战在于 Car 模型没有公司的 id,并且 pivot table 没有汽车的名称,它只包含 car_id 和 company_id.

非常感谢

我的车模

class Car extends Model
{
    protected $fillable = ['name'];

    protected $dates = ['purchased_at'];

    public function company(){
        return $this->belongsToMany('App\Company')->withPivot('quantity', 'purchased_at')->withTimestamps();
    }
}

我的公司模型

class Company extends Model implements AuthenticatableContract, CanResetPasswordContract
{
    use Authenticatable, CanResetPassword;

    protected $table = 'companies';

    protected $hidden = ['password', 'remember_token'];

    public function setPasswordAttribute($password){
        $this->attributes['password'] = bcrypt($password);
    }

    public function cars(){
        return $this->belongsToMany('App\Car')->withPivot('quantity', 'purchased_at')->withTimestamps();
    }

}

我的汽车控制器

class CarsController extends Controller
{


    public function store(CarRequest $request)
    {
        $car = new Car;
        $car->name = $request->input('name');
        $car->save();
        $car->company()->attach(Auth::user()->id,array('quantity' => $request->input('quantity'),'purchased_at' => \Carbon\Carbon::now()));

        return Redirect('companies/'. Auth::user()->id .'/cars')->with(['success'=>'You have just created a new car!']);
    }
}

我的汽车请求

class CarRequest extends Request
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'name'          => 'required | unique:car_company,car_id',
            'quantity'      => 'required'
        ];
    }
}

我找到了解决办法。基本上,我们可以有条件地修改规则条目。在这种情况下,我在经过身份验证的公司内部查找汽车,如果汽车名称存在,那么我将规则更改为在汽车 table 上是唯一的,这将失败,因为已经有一辆同名汽车这个table。 这是我的 CarRequest class:

中的新规则函数
public function rules()
{
    $rules = [
        'quantity'      => 'required',
        ]; 
    $car = Auth::user()->cars->where('name', $this->input('name'));

    if (count($car) === 0)
    {
        $rules['name'] = 'required';
    }
    else{
        $rules['name'] = 'required | unique:cars';
    }
    return $rules;
}