我有一个租赁公司有车的系统。许多租赁公司都可以买到一辆汽车。所以这是一种多到多的关系。
我想向这些公司提供购买新车时增加新车的可能性。如果汽车已经存在,系统就不会创建它,但是会闪现一条错误信息,说他们已经有了那辆车。
如何使用添加的汽车名称字段的唯一验证规则?挑战在于,汽车型号没有公司的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'
];
}
}发布于 2015-08-28 22:09:49
我找到了解决办法。基本上,我们可以有条件地修改规则条目。在本例中,我在经过身份验证的公司中查找汽车,如果汽车名称存在,那么我将把规则更改为cars表中的唯一规则,这将失败,因为这个表中已经有一个同名的汽车。下面是我的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;
}https://stackoverflow.com/questions/32199441
复制相似问题