Reputation: 7664
I am building a RESTful api using Laravel. I am confused on how to do the routing.
I have the following api controller
class APIController extends BaseController{
public function sendMsg($authid, $roomid, $msg){
}
public function getMsg($roomid, $timestamp){
}
}
The URL format I want this to be accessible looks like this:
http://example.com/api/{functionName}/{parameter1}/{parameter2}/.../
Here, in the first parameter, I will have the function name which should map to the function in the controller class and following that the parameters the controller needs.
For example
To access the sendMsg()
function, the url should look like this:
http://example.com/api/sendMsg/sdf879s8/2/hi+there+whats+up
To access the getMsg()
function, the url should look like
http://example.com/api/getMsg/2/1395796678
I can write one route for each function name like so:
Route::get('/api/sendmsg/{authid}/{msg}', function($authid, $msg){
//call function...
});
and same for the other function. This if fine but is there a way to combine all function to the APIController in one route?
Upvotes: 1
Views: 7783
Reputation: 146191
Yes, you can combine all the function to your APIController
in one route by using a resourceful controller which is best suited for building an API
:
Route::resource('api' ,'APIController');
But, technically, it's not one route at all, instead Laravel
generates multiple routes
for each function, to check routes, you may run php artisan routes
command from your command prompt/terminal.
To, create a resourceful controller
you may run the following command from your command line:
php artisan controller:make APIController
This will create a controller with 6 functions (skeleton/structure only) and each function would be mapped to a HTTP
verb. It means, depending on the request type (GET/POST etc) the function will be invoked. For example, if a request is made using http://domain.com/api
using GET
request then the getIndex
method will be invoked.
public function getIndex()
{
// ...
}
You should check the documentation for proper understanding in depth. This is known as RESTful
api.
Upvotes: 2