laravel中表单验证的正确方法是什么?

时间:2017-06-27 09:11:40

标签: laravel

我刚刚创建了表单,操作是PagesController@check,验证如下:

@extends('layout')

@section('content')

<div class = "container">
    {!! Form::open(['action' => 'PagesController@check' , 'method' => 'POST']) !!}

        <div class = "form-group">
            {{ Form::label('country','Country')}}
            {{ Form::text('country','', ['class' => 'form-control' , 'placeholder' => ''])}}
        </div>  

        <div class = "form-group">
            {{ Form::label('age','Age')}}
            {{ Form::number('age','', ['class' => 'form-control' , 'placeholder' => ''])}}
        </div>  

        <div class = "form-group">
            {{ Form::label('marks','Marks')}}
            {{ Form::number('marks','', ['class' => 'form-control' , 'placeholder' => ''])}}
        </div>  

        <div class = "form-group">
            {{ Form::label('description','Description')}}
            {{ Form::textarea('description','', ['class' => 'form-control' , 'placeholder' => ''])}}
        </div>  

        {{ Form::submit('Submit' , ['class' => 'btn btn-primary'])}}

    {!! Form::close() !!}
</div>
@endsection

check()中的PagesController方法是这样的:

    public function check(Request $request){
        $this->validate($request, [
            'country' => 'required',
            'age' => 'required',
            'marks' => 'required',
            'description' => 'required'

            ]);
        return 123;

   }

为什么它会抛出以下错误:

  

(2/2)ErrorException
  Action App \ Http \ Controllers \ PagesController @ check未定义。 (查看:C:\ wamp64 \ bin \ apache \ apache2.4.23 \ htdocs \ website \ resources \ views \ profiles.blade.php)

以下是整个PagesController控制器:

class PagesController extends Controller
{
    public function home() {
        return view('welcome');
    }

    public function about() {
        $title = 'This is the about page';
        return view('about')->with('title',$title);
    }

    public function show() {
        $yomads = person::all();
        return view('show')->with('yomads',$yomads);
    }

    public function profiles(){
       return view('profiles');
    }

    public function check(Request $request){
        $this->validate($request, [
            'country' => 'required',
            'age' => 'required',
            'marks' => 'required',
            'description' => 'required'

            ]);
        return 123;

   }
}

1 个答案:

答案 0 :(得分:1)

错误很可能与app/Http/routes.php中的路径(或缺少路径)有关 - 检查它是否在那里正确定义。

此外,最好创建自定义请求类。看看Form Request Validation

这些可以由工匠生成:

php artisan make:request Profile

然后在使用标准请求时使用它:

public function check(ProfileRequest $request) {
[...]