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');

Tip

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
        ->where('name',
          'like',
          '%'.$request->get('name').'%')
        ->get();
    }

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

    Tip

    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:

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}]