Adding a Poll record with validation in restful api

Step 01: Setting up route for store() method in PollController in routes/api.php

Route::post( '/polls', [PollController::class,'store']);


Step 02:
Adding store() method in PollController

namespace App\Http\Controllers;

use App\Models\Poll;

class PollController extends Controller
{
    //
    public function index() {
        return response()->json(Poll::get(),200);
    }    

    public function show($id) {
        return response()->json(Poll::find($id),200);
    } 

    public function store() {
       $poll = Poll::create(request()->all());
       // 200 for all success, 201 only for new resource creation
       return response()->json($poll,201);
    }	
}


Step 03:
Adding validation rules for input requests inside store() method

// at the top 
use Illuminate\Support\Facades\Validator;

public function store() {

	$rules = [
		'title' => 'required|max:255',
	];
	$validator = Validator::make(request()->all(),$rules);
	//dd($validator->fails());
	if( $validator->fails() ) {
		return response()->json($validator->errors(),400);
	}
	$poll = Poll::create(request()->all());
	// 200 for all success, 201 only for new resource creation
	return response()->json($poll,201);
} 


Now in postman application under "Body" tab selecting "x-www-form-urlencode" putting key value pair as table column and value setting HTTP verb as POST if url is browsed like below this in local server the input given poll will be saved to poll table of the database.

EndPoint URL: http://localhost:8000/api/polls
HTTP verb: POST
Input:
key: title
value: Poll saving from postman

Related Posts


Building RESTful APIs in Laravel

Seeding Poll data

Seeding Question data for a poll

Pagination for poll in restful api

Uploading image in restful api