Deleting a Poll record with validation

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

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


Step 02:
adding delete() 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);
    }
    
    public function delete($id) {
        $poll = Poll::find($id);
        if(is_null($poll)){
            return response()->json(null,404);
        }         
        $poll->delete();
        // 204 means resource deleted successfully
        return response()->json(null,204);
    }    
}


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

Now in postman setting HTTP verb as DELETE if url is browsed like below in local server the input given poll will be delete from poll table of the database.

EndPoint URL: http://localhost:8000/api/polls/2
HTTP verb: DELETE

Here, if input is not matched 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