Laravel throw Error from Model if the Condition Fails

吃可爱长大的小学妹 提交于 2019-12-12 14:40:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!