Priska Aprilia Priska Aprilia - 2 years ago 314
PHP Question

Laravel routes with unlimited parameters for RESTful API

I am building a RESTful API using Laravel 5.1.
The default route would be

. The user is allowed to create a url service using as many as parameters as she wants let's say

How do I make a single route to point to a single Controller, so the service will be handled in a single controller?

Note : At first the application just needs to know whether the service exists or not by comparing the
with stored service in the database. As for the service itself, it can be queried into the database later.

I read that we can use
in Laravel 4, how about Laravel 5.1 ?

I have tried :

Route::resource('/api/*', 'APIServiceController');
but it does not work for unlimited parameters

or is it possible to do it like this

Route::group(['prefix' => 'api'], function () {
//what should I put in the closure, how can I redirect it to a single controller

Answer Source

Write your route as below:-

Route::group(['prefix' => 'api'], function () {
    // this route will basically catch everything that starts with api/routeName 
    Route::get('routeName/{params?}', function($params= null){
        return $params;
    })->where('params', '(.*)');

Redirect to controller,

Route::group(['prefix' => 'api'], function () {
    Route::get('routeName/{params?}', 'YourController@action')->where('params', '(.*)');

If you want to make routeName dynamic then just write it in curly bracket as below:-

Route::get('{routeName}/{params?}', 'YourController@action')->where('params', '(.*)');

Hope it will help you :-)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download