简体   繁体   中英

Laravel throw Error from Model if the Condition Fails

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?

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.

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/

This works for me

return abort(500, 'Somthing went wrong');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM