Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4 - URI Parameters in Implicit Controllers

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()

like image 305
Paulo Coghi Avatar asked Oct 28 '14 00:10

Paulo Coghi


2 Answers

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

like image 85
Ceeee Avatar answered Oct 11 '22 13:10

Ceeee


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');

});
like image 26
NiRR Avatar answered Oct 11 '22 14:10

NiRR