【发布时间】: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