Martin Fejes
Martin Fejes

Reputation: 677

How do RESTful controllers work in Laravel 4, how to use them properly?

I'm new to MVC's (this is my first time using one in a real scenario) and I am a little bit confused about how controllers (should) work.

After reading the Laravel documentation, I came to the conclusion that for general tasks like handling loading the sites (different sites are connected together), pages, admin, etc. I need RESTful controllers.

For the simple tasks it worked. It was easy and very fun to use. I had a Route like this:

Route::controller('admin', 'AdminController'); 

I had functions like

public function getProduct($id) 

and it worked. (It was used to get a specific product: ../admin/product/1)

Now I want something more complex. Like

../sites/loadsite/mysite/mypage/mysubpage/123?myoption=yes

How do I do this? How do I begin, how to approach the problem? Do I have to use Route::get() for every single thing or is there a "nicer" way of doing this?

Upvotes: 1

Views: 331

Answers (2)

matpop
matpop

Reputation: 2020

The "nicer" way is resource controllers - which of course may be combined with route prefixing and filters (e.g. authentication filters), etc.

Inside the methods of resource controllers, you can retrieve additional input (the option in the query string of your example) and process it with validation and whatever you want.

Upvotes: 2

Kenny H
Kenny H

Reputation: 21

Laravel provides the "Resource Controllers" helper for generating RESTful routes for corresponding controller methods:

http://laravel.com/docs/controllers#resource-controllers

You can use this to easily create the standard REST routes for a given model, or, as shown in the example provided at laravel.com, you can restrict to only certain routes. The table they provide demonstrates how given paths map to given actions / controller methods.

Regarding the example url you give: ../sites/loadsite/mysite/mypage/mysubpage/123?myoption=yes, I'll break the question into two pieces, the url and query string:

Regarding the URL /sites/loadsite/mysite/mypage/mysubpage/123. This would not be considered by many to be a "RESTful" route. Instead of pages and subpages, you should be thinking in terms of models, and sometimes submodels. It is commonly considered best practice to avoid deeply nested routes, which typically means anything more than a single layer of depth: /model/{id}/submodel/[id]

Regarding the query string at the end of the url: ?myoption=yes: Laravel provides access to query string parameters by using the Input::get("Param") function. You do not have to designate query string params in your routes, they can simply be accessed in your controller method.

Upvotes: 2

Related Questions