5

How to get URI parameters in methods inside a implicit controller?

First, I define a base route:

Route::controller('users', 'UserController');

Then,

class UserController extends BaseController {

    public function getIndex()
    {
        //
    }

    public function postProfile()
    {
        //
    }

    public function anyLogin()
    {
        //
    }

}

If I want to pass aditional parameters in URI, like http://myapp/users/{param1}/{param2} , how can I read param1 and param2 inside the respectve method? In this example, getIndex()

Paulo Coghi
  • 13,724
  • 14
  • 68
  • 90

2 Answers2

7

If you want to have URL like http://myapp/users/{param1}/{param2} you need to have in your controller like this:

Route::get('users/{param1}/{param2}', 'UserController@getIndex');

and access it:

class UserController extends BaseController {

    public function getIndex($param1, $param2)
    {
        //
    }

}

but hey, you can also do something like this, the routes will be same:

class UserController extends BaseController {

    public function getIndex()
    {
        $param1 = Input::get('param1');
        $param2 = Input::get('param2');

    }

}

but your URL would be something like: http://myapp/users?param1=value&param2=value

Ceeee
  • 1,392
  • 2
  • 15
  • 32
  • 1
    Probably this is the only way. I would like to benefit from the Implicit Controllers in this case too, but it seems that we can't do this. If no one else provide a better solution, you get the ponts. :) – Paulo Coghi Oct 28 '14 at 04:49
  • 1
    hmm, many people says implicit controllers are hard to read and guess for your project's new developers(in case you'll have a new one). most people(including my idol jeffrey way) suggest using resource controller or just the normal way of adding controllers(ex Route::post or Route::put). but it's the developers' preference and we all have different preferences :) – Ceeee Oct 28 '14 at 07:29
2

Here is a way of creating a directory like hierarchy between models (nested routing)

Assume Album has Images, we would like an album controller (to retrieve album data) and an image controller (to retrieve image data).

Route::group(array('before' => 'auth', 'prefix' => 'album/{album_id}'), function()
{
    // urls can look like /album/145/image/* where * is implicit in image controller.
    Route::controller('image', 'ImageController');

});

Route::group(array('before' => 'auth'), function()
{
    // urls can look like /album/* where * is implicit in album controller.
    Route::controller('album', 'AlbumController');

});
NiRR
  • 4,782
  • 5
  • 32
  • 60