简体   繁体   中英

Laravel routes with multiple optional parameters

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


So... how can I write my routes so that it can handle the dynamic number and different parameters need?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM