Public interface
The final piece of our web service is the public interface that will allow a client app to request the listing data. Since the Vuebnb listing page is designed to display one listing at a time, we'll at least need an endpoint to retrieve a single listing.
Let's now create a route that will match any incoming GET requests to the URI /api/listing/{listing}
where {listing}
is an ID. We'll put this in the routes/api.php
file, where routes are automatically given the /api/
prefix and have middleware optimized for use in a web service by default.
We'll use a closure
function to handle the route. The function will have a $listing
argument, which we'll type hint as an instance of the Listing
class, that is, our model. Laravel's service container will resolve this as an instance with the ID matching {listing}
.
We can then encode the model as JSON and return it as a response.
routes/api.php
:
<?php use App\Listing; Route::get('listing/{listing}', function(Listing $listing) { return...