繁体   English   中英

如果条件失败,Laravel 从 Model 抛出错误

[英]Laravel throw Error from Model if the Condition Fails

我正在 Model 中进行所有验证

我的规则是

public static $rules = array(
        'VehicleNumber' => 'required|unique:vehicle', 
        'NumberSeats' => 'required', 
        'VehicleType' => 'required', 
        'MaximumAllowed' => 'numeric|max:3',
        'VehicleCode' => 'required|unique:vehicle');
}

但是为了更改文件名并检查其大小,我在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());
    }
}

有条件

if($InsurancePhoto && Input::file('InsurancePhoto')->getSize() < '1000')

如果存储图片失败,则不会设置属性。

但是在这种情况下我怎样才能将错误抛给用户呢?

您可以抛出Exception并显示错误消息。

模型

if($InsurancePhoto && Input::file('InsurancePhoto')->getSize() < '1000') {
    // process image
} else {
    throw new \Exception('Error message');
}

在控制器(您调用验证)中,您可以捕获此异常并将其打印给用户。

getSize()返回整数,所以你不应该使用字符串进行比较,因为你用单引号写了1000。 您可以在laravel中创建自己的自定义验证。 检查此链接stackoverflowhttp://culttt.com/2014/01/20/extending-laravel-4-validator/

这对我有用

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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