【问题标题】:unique name rule validation based on pivot table laravel基于数据透视表 laravel 的唯一名称规则验证
【发布时间】:2015-11-18 21:19:17
【问题描述】:

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

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

如何对正在添加的汽车的名称字段使用唯一验证规则?挑战在于 Car 模型没有公司的 id,数据透视表也没有汽车的名称,它只包含 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'
        ];
    }
}

【问题讨论】:

  • 添加您的代码,请试用
  • @Daenu 我按要求编辑了我的问题。

标签: validation laravel laravel-5 unique pivot-table


【解决方案1】:

我找到了解决方案。基本上,我们可以有条件地修改规则条目。在这种情况下,我在经过身份验证的公司内部查找汽车,如果汽车名称存在,那么我将规则更改为汽车表上的唯一性,这将失败,因为该表中已经存在同名汽车。 这是我的 CarRequest 类中的新规则函数:

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

【讨论】:

  • 你知道吗?你可以接受你自己的答案!
猜你喜欢
  • 2015-07-09
  • 2015-02-27
  • 1970-01-01
  • 2018-05-24
  • 1970-01-01
  • 2018-06-26
  • 2022-06-11
  • 2016-12-06
  • 1970-01-01
相关资源
最近更新 更多