Moving beyond CRUD

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 withinAccommodationsController:

Route::get('search', '[email protected]');
Route::resource('accommodations', 'AccommodationsController');


In this case, the GET method would be preferred instead of the POST method, as it can be bookmarked and recalled later.

Now, we will write our search function:

public function search(Request $request, Accommodation $accommodation)
    return $accommodation

There are several mechanisms here:

  • The Request object that contains the variables from the GET request is type-hinted and then injected into the search function
  • The Accommodation model is type-hinted and then injected into the search function
  • The where() method from the fluent query builder is called on the eloquent model$accommodation
  • The name parameter is used from the request object
  • The get() method is used to actually perform the SQL query


    Note that some of the query builder and eloquent methods return an instance of the query builder, while the others execute the query and return the result. The where() method returns an instance of the query builder, while the get() method executes the query.

  • The resulting eloquent collection is returned and automatically encoded into JSON

The GET request, therefore, is as follows:

The resultant JSON would look something like this:

"name":"Lovely Hotel",
"description":"Lovely Hotel Greater Pittsburgh",
"created_at":"2015-03-13 22:00:23",
"updated_at":"2015-03-13 22:00:23",
"name":"Lovely Hotel",
"description":"Lovely Hotel Greater Philadelphia",
"created_at":"2015-03-11 21:43:31",
"updated_at":"2015-03-11 21:43:31",