03.12.2015 Views

laravel4cookbook

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

API 133<br />

1 curl -X POST -d "name=foo&description=a+day+of+foo&started_at=2013-10-03+09:00&en\<br />

2 ded_at=2013-10-03+12:00" http://dev.tutorial-laravel-4-api:2080/event<br />

..now, when we request the index() action, we should see the new event has been added. We can<br />

retrieve this event individually with a request similar to this:<br />

1 curl http://dev.tutorial-laravel-4-api:2080/event/1<br />

There’s a lot going on here. Remember how we bound the model to a specific parameter name (in<br />

app/routes.php)? Well Laravel 4 sees that ID value, matches it to the bound model parameter and<br />

fetches the record from the database. If the ID does not match any of the records in the database;<br />

Laravel will respond with a 404 error message.<br />

If the record is found; Laravel returns the model representation to the action we specified, and we<br />

get a model to work with.<br />

Let’s update this event:<br />

1 curl -X PUT -d "name=best+foo&description=a+day+of+the+best+foo&started_at=2013-1\<br />

2 0-03+10:00&ended_at=2013-10-03+13:00" http://dev.tutorial-laravel-4-api:2080/even\<br />

3 t/1<br />

Notice how all that’s changed is the data and the request type — even though we’re doing something<br />

completely different behind the scenes.<br />

Lastly, let’s delete the event:<br />

1 curl -X DELETE http://dev.tutorial-laravel-4-api:2080/event/1<br />

.<br />

Feel free to set the same routes and actions up for categories and sponsors. I’ve not covered them<br />

here, for the sake of time, but they only differ in terms of the fields.<br />

Authenticating Requests<br />

So far we’ve left the API endpoints unauthenticated. That’s ok for internal use but it would be far<br />

more secure if we were to add an authentication layer.<br />

We do this by securing the routes in filtered groups, and checking for valid credentials within the<br />

filter:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!