If one of the requirements of the software application to be built is able to search for an accommodation, then we can easily add a search function. The search function will find accommodations by using a name
string. One way to do this is to add a route to the routes.php
file. This will map a GET
call to search for a new search()
function contained within AccommodationsController
:
Route::get('search', 'AccommodationsController@search'), Route::resource('accommodations', 'AccommodationsController'),
Now, we will write our search function:
public function search(Request $request, Accommodation $accommodation) { return $accommodation ->where('name', 'like', '%'.$request->get('name').'%') ->get(); }
There are several mechanisms here:
Request
object that contains the variables from the GET
request is type-hinted and then injected into the search functionAccommodation
model is type-hinted and then injected into the search
functionwhere()
method from the fluent query builder is called on the eloquent model $accommodation
name
parameter is used from the request
objectget()
method is used to actually perform the SQL queryThe GET
request, therefore, is as follows:
http://www.hotelwebsite.com/search-accommodation?name=Lovely
The resultant JSON would look something like this:
[{"id":3, "name":"Lovely Hotel", "description":"Lovely Hotel Greater Pittsburgh", "location_id":1, "created_at":"2015-03-13 22:00:23", "updated_at":"2015-03-13 22:00:23", "deleted_at":null}, {"id":4, "name":"Lovely Hotel", "description":"Lovely Hotel Greater Philadelphia", "location_id":2, "created_at":"2015-03-11 21:43:31", "updated_at":"2015-03-11 21:43:31", "deleted_at":null}]