控制器中的 Laravel 5 验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42650185/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:29:53  来源:igfitidea点击:

Laravel 5 Validation in controller

phplaravellaravel-5.3

提问by Przemek

I have 2 methods in my Controller and I need to validate it but I don't know how.

我的控制器中有 2 个方法,我需要验证它,但我不知道如何进行。

1st method which should allow all image extensions:

第一种方法应该允许所有图像扩展:

public function testing(Request $request) {
    if($request->hasFile('img')) {
        $image = Input::file('img');
        $filename = time() . '.' . $image->getClientOriginalExtension();
        $path = public_path('images/' . $filename);
        Image::make($image->getRealPath())->resize(200, 200)->save($path);
        $file = $request->file('img');
        return ['url' => url('images/' . $filename)];
    }
}

2nd method which should only allow 1 word and if there is space, trim it into 1 word:

第二种方法应该只允许 1 个单词,如果有空格,则将其修剪为 1 个单词:

public function postDB(Request $request) {
    $newName = $request->input('newName');
    $websites = new Website();
    $websites->name = $newName;
    $websites->save();
    return redirect('template')->with('status', 'Website has been saved successfully!');
}

回答by Odin Thunder

First write new Request for your data

首先为您的数据编写新的请求

php artisan make:request ImageRequest

Than write in ImageRequest:

比写在ImageRequest

public function authorize()
{
    return true;
}

public function rules()
{
    return [
       'img' => 'file|image',
    ]    
}

If you want to customize error messages:

如果要自定义错误消息:

public function messages()
    {
        return [
            'img.image' => 'Some custom message ...',

        ];
    }

Last inject request to your method (don`t forget about use App\Http\Requests):

最后向您的方法注入请求(不要忘记使用 App\Http\Requests):

public function testing(Requests\ImageRequest $request) {
    //for retrieving validation errors use:
      $imgErrors = $errors->first('img'); 
}

More informationabout Form Request Validation

有关表单请求验证的更多信息

Or you can use Validatorfacade (don`t forget about use Validator):

或者你可以使用Validator门面(不要忘记使用 Validator):

$validator = Validator::make(
            $image, [
                'img' => 'file|image',
            ]
        );

More informationabout A Note On Optional Fields

更多信息有关的一个注可选字段