问题
I am doing all the validations in Model
My Rule is
public static $rules = array(
'VehicleNumber' => 'required|unique:vehicle',
'NumberSeats' => 'required',
'VehicleType' => 'required',
'MaximumAllowed' => 'numeric|max:3',
'VehicleCode' => 'required|unique:vehicle');
}
But for changing the file name and checking its size i am handling in a SetFooAttribute
public function setInsurancePhotoAttribute($InsurancePhoto)
{
if($InsurancePhoto && Input::file('InsurancePhoto')->getSize() < '1000')
{
$this->attributes['InsurancePhoto'] = Input::get('VehicleCode') . '-InsurancePhoto.' . Input::file('InsurancePhoto')->getClientOriginalExtension();
Input::file('InsurancePhoto')->move('assets/uploads/vehicle/', Input::get('VehicleCode') . '-InsurancePhoto.' . Input::file('InsurancePhoto')->getClientOriginalExtension());
}
}
There in the Condition
if($InsurancePhoto && Input::file('InsurancePhoto')->getSize() < '1000')
If it fails the Storing of Image, Setting Attribute won't be done.
But How can i throw the Error to the User in this Case ?
回答1:
You can throw Exception with error message.
Model
if($InsurancePhoto && Input::file('InsurancePhoto')->getSize() < '1000') {
// process image
} else {
throw new \Exception('Error message');
}
In controller (where you call validation) you can catch this exception and print it to user.
回答2:
getSize() return integer so you should not use string for comparison as you have written 1000 in single quotes. You can create your own custom Validation in laravel. Check this links stackoverflow and http://culttt.com/2014/01/20/extending-laravel-4-validator/
来源:https://stackoverflow.com/questions/27645655/laravel-throw-error-from-model-if-the-condition-fails