Laravel表单验证器错误

时间:2017-01-06 06:07:42

标签: php laravel api validation laravel-5.3

我想在将数据存储到数据库之前验证输入字段,因此我浏览了laravel文档并遵循这些

  1. php artisan make:request StoreLessons
  2. StoreLessons

    public function rules()
        {
            return [
                'title' => 'required|unique:lesson',
                'body' => 'required',
            ];
        }
    
  3. 在我的控制器中

  4. namespace App\Http\Controllers;
    
    use Response;
    use App\lesson;
    use Illuminate\Http\Request;
    use App\Acme\Transformers\LessonTransformer;
    use Illuminate\Support\Facades\Input;
    use App\Http\Requests\StoreLessons;
    
    class LessonsController extends ApiController 
    {
    
        protected $lessonTransformer;
    
        function __construct(LessonTransformer $lessonTransformer) 
        {
            $this->lessonTransformer = $lessonTransformer;
        }
    
        //fetch all and pass a metadata 'data' 
        public function index() 
        {
            $lessons = Lesson::all();
    
            return $this->respond([
                'data' => $this->lessonTransformer->transformCollection($lessons->all())
            ]);
        }
    
        //add a new lesson to lessons table
        public function store(StoreLessons $request) 
        {
            Lesson::create($request->all());
    
            //Lesson::create(input::all());
    
            return $this->respondCreated('Lesson created successfully');
        }
    
    
    }
    

    现在我收到此错误

    QueryException in Connection.php line 770:
    SQLSTATE[42S02]: Base table or view not found: 1146 Table 'laravel_api.lesson' doesn't exist (SQL: select count(*) as aggregate from `lesson` where `title` = the)
    

    我不知道为什么它正在寻找lesson表我有lessons

    store()函数可以使用默认验证

    //this works fine but i wan to do the validation 
        public function store() 
        {
            if (! input::get('title') or ! input::get('body')) {
                return $this->respondBadRequest();
            }
    
            Lesson::create(input::all());
    
            return $this->respondCreated('Lesson created successfully');
        }
    

    谢谢

2 个答案:

答案 0 :(得分:2)

unique:table,column,except,idColumn

唯一语法如上所述,传递的第一个参数是表名。

public function rules() { 
    return [ 'title' => 'required|unique:lesson', 'body' => 'required', ];
}

此处的唯一规则会查找表lesson。尝试将其更改为lessons

答案 1 :(得分:0)

请在相关的模型类名之后写下面的行。

类xyz扩展了Model { 受保护的$ table ='课程';

代码---

<强>}

试试这个。