Wednesday, April 12, 2017

How to validate POST data in Laravel 5.4?

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.



via redshot

Advertisement