Editing a Poll record with validation

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

Route::put( '/polls/{id}', [PollController::class,'update']);


Step 02:
adding update() method in PollController with missing row validation

namespace App\Http\Controllers;

use App\Models\Poll;
use Illuminate\Support\Facades\Validator;

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

    public function show($id) {
        $poll = Poll::find($id);
        if(is_null($poll)){
            return response()->json(null,404);
        }
        return response()->json($poll,200);
    }
    
    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);
    } 
    
    public function update($id) {
        $poll = Poll::find($id);
        if(is_null($poll)){
            return response()->json(null,404);
        }        
        $poll->update( request()->all() );
        return response()->json($poll,200);
    }  
}


From above, we can see update() method is almost same as show() mehtod.

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 PUT if url is browsed like below this in local server the input given poll will be updated to poll table of the database.

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

If input is empty then it will return existing poll data unchanged. Also if input is not matched with database table then 404 response code will be returned with empty json array {}

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