Searching Poll records with query string and using eloquent when

We will be changing index() method like below of PollController for this purpose

//In PollController.php
public function index() { //dd(request('search_title')); $polls = Poll::when( request('search_title'), function ($query) { $query->where('title', 'like', '%'.request('search_title').'%' ); })->get(); return response()->json($polls,200); }


Now in postman setting HTTP verb as GET if url is browsed like below with query string search_title=rus in local server it will return those number of rows which have "rus" in the poll title fields assuming there are rows with such string.

EndPoint URL: http://localhost:8000/api/polls?search_title=rus
HTTP verb: GET

Note, if query string is not given all the records of polls will be returned.

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