Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to build a Laravel route that requires a specific URL query parameter?

Let's say I have URLs like this:

  1. localhost/admin/users/ <--- Main Admin Users page
  2. localhost/admin/users/?data=refresh <---- A typical ajax request made from that page

And a simple controller like this:

class UsersController extends Controller {

     public function index()

         // call some services
         // return a view
     }

     public function dataRefresh {

         // call some services
         // return some JSON
     }
}

And here's my routes.php I'm working on:

    Route::get('admin/users', array('as' => 'admin.users', 'uses' => 'Admin\Users\UsersController@index'));
    Route::get('admin/users????' , array('before' => 'ajax', 'as' => 'admin.users', 'uses' => 'Admin\Users\UsersController@dataRefresh'));

What can I do in my second route to require a URL query parameter ?data and furthermore require it is set to data=refresh? And how do I ensure it doesn't conflict with the other route?

Note: I'm aware this may not be considered "pretty URL" by some. I do implement pretty URLs / slugs when appropriate, however I also think there are many cases where the query parameters are more clearer and cleaner (ie. give a user a clear understanding of what part of the page's URL is for filtering the data in a datagrid...and assures a user the parameters can be removed without causing the page to break or go missing). Google does this themselves, as well as many other reputable sites.

Note: I have applied an ajax route filter to the second route. I've also set the route to point towards the dataRefresh method in my controller.

This is as far as I've got. Any ideas?

like image 299
prograhammer Avatar asked Oct 20 '22 12:10

prograhammer


1 Answers

Laravel doesn't use the query part of a uri for routing, for localhost/admin/users?data=refresh you may use something like this:

Route::get('admin/users', function(){
    $data = Input::get('data');
});

You can make a request to the route using localhost/admin/users?data=refresh. You can declare your route like this:

Route::get('admin/users' , array('before' => 'ajax:data', 'as' => 'admin.users', 'uses' => 'Admin\Users\UsersController@dataRefresh'));

Here, refresh is passed to route filter and is available in third argument ($param) so you can retrieve refresh in $param. Create the filter as given below:

Route::filter('ajax', function($route, $request, $param){

    // This will give query string 'refresh'
    // if you passed it as http://domain.com?data=refresh
    $data = $request->get($param);

    // You can retrieve the $param, third argument
    // if you pass a parameter, i.e. 'refresh'
    // param will contain 'refresh'
});
like image 51
The Alpha Avatar answered Oct 27 '22 11:10

The Alpha