Similar to Poll resource we will be implementing endpoints for question resources that is browsing, adding, reading, editing and deleting record for question resource. But
instead of implementing all of these in several posts we will be doing that in one long post.
Step 01: setting up routes in routes/api.php for question resource with a one liner method apiResource() of Route facade which will have these index(), store(), update() and delete() method definitions be default
Route::apiResource( 'questions', QuestionController::class );
Step 02: Setting up QuestionController.php like below under app/Http/Controllers
namespace App\Http\Controllers;
use App\Models\Question;
class QuestionController extends Controller
{
public function index()
{
//
return response()->json(Question::get(),200);
}
public function store()
{
//
return response()->json(Question::create(request()->all()),201);
}
public function show(Question $question)
{
//
return response()->json($question,200);
}
public function update(Question $question)
{
//
return response()->json($question->update(request()->all()),200);
}
public function destroy(Question $question)
{
//
return response()->json($question->delete(),204);
}
}
Now like previously if we use postman to check all the endpoints such as browsing, adding, reading, editing and deleting record for question resource we will need to do it by below urls
Browsing all question records
http://localhost:8000/api/questions
Adding one question record
http://localhost:8000/api/questions
HTTP Verb: POST
Input:
title: new question
poll_id: 1
HTTP Verb: GET
Reading one question record
http://localhost:8000/api/questions/2
HTTP Verb: GET
Editing one question record
http://localhost:8000/api/questions/2
HTTP Verb: PUT
Input:
title: new question updated
poll_id: 1
Deleting one question record
http://localhost:8000/api/questions/2
HTTP Verb: DELETE