duankun9280 2017-04-13 05:37
浏览 131
已采纳

如何在Laravel 5.4中验证POST数据?

I am testing an API in Laravel 5.4. I am now in the part of storing a record via API. I am having some issues on how to use Request::input() or Input::get() to validate POST data.

LessonsController.php

    <?php

    namespace App\Http\Controllers;

    use App\Http\Requests;
    use App\Lesson;
    use App\Acme\Transformers\LessonTransformer;
    //use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Input;


use App\Http\Controllers\Controller;

class LessonsController extends ApiController
{

    /**
     * @var Acme\Transformers\LessonTransformer
     */
    protected $lessonTransformer;

    function __construct(LessonTransformer $lessonTransformer)
    {
        $this->lessonTransformer = $lessonTransformer;
       // $this->middleware('sentry.auth')->only('post'); // basic level of protection for creating a lession
    }


    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     * If we are using basic authentication, we should be using SSL
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store()
    {

        if( ! Input::get('title') || ! Input::get('body')){
            return $this->setStatusCode(422)->respondWithError('Parameters failed validation for a lesson.');
        }

        Lesson::create($request->all());

        return $this->respondCreated('Lesson successfully created.');

    }

    /**
     * Display the specified resource.
     * 
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $lesson = Lesson::find($id);

        if( ! $lesson) {

            return $this->respondNotFound('Lesson does not exist');


        }

        return $this->respond([

            'data' => $this->lessonTransformer->transform($lesson)

        ]);

    }

}

When I test my code above with POSTMAN using POST request. I am prompted with "{"error":"Parameters failed validation for a lesson.","status_code":422}" . I receive an error when I try to add data or I don't add data.

Do you have any idea how to correct my store() code? Any help is appreciated.

  • 写回答

3条回答 默认 最新

  • duanjiao7440 2017-04-15 07:51
    关注

    The problem with my code above is that it does not have the $request var in the store() method.

    In my code be below, the Request class is now injected into store method.

    public function store(Request $request)
    {
    
        if (! $request->input('title') or ! $request->input('body') )   
        {
             return $this->respondUnprocessableEntity('Parameters failed validation for a lesson.');
        }
    
        Lesson::create($request->all());
    
        return $this->respondCreated('Lesson successfully created.');
    
    }
    

    Note: In postman, select x-www-form-urlencoded in Body

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • duancong2965 2017-04-13 05:52
    关注

    To validate form data in Laravel simply use "Laravel Form Requests". This allows you to validate your form data in request using some predefined validation rules of Laravel and if you need you can also create you custom laravel validation logic.

    According to Laravel docs:

    Form requests are custom request classes that contain validation logic.

    It will simplify your validation logic, make your code neat and let you handle complex validations.

    评论
  • doujin8673 2017-04-13 06:24
    关注

    Try this, might help

    public function store(Request $request)
        {
        if( ! $request->has('title') || ! $request->has('body')){
            return $this->setStatusCode(422)->respondWithError('Parameters failed validation for a lesson.');
        }
    
        Lesson::create($request->all());
    
        return $this->respondCreated('Lesson successfully created.');
    
        }
    
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 设计程序,利用函数getCharacterCnt,实现求解出str所指字符串中指定字符的个数,并返回此值。
  • ¥15 设计程序,实现管理30个学生5门课程的成绩,功能模块要求如下。
  • ¥15 B660主板安装xp系统老是出现错误怎么办
  • ¥15 定义过的变量报错未定义
  • ¥15 如何在EXCEL某单元格中查找是否存在另一列中的内容。
  • ¥50 非对称加密(相关搜索:密码学)
  • ¥15 关于非编程寻迹小车的分析
  • ¥15 java导出EXCEL这里已经执行成功了,但是流浪器没有下载
  • ¥15 帮我把代码改的能正常运行就行
  • ¥50 有限元修正、模型修正、最小二乘法,详细步骤