Alex
Alex

Reputation: 7688

Laravel routes for RESTful controllers

Having the following controller:

class Admin_Images_Controller extends Admin_Controller
{
    public $restful = true;

    public function __construct()
    {
        parent::__construct();
    }

    public function get_index($id)
    {
        echo $id;
    }

I don't understand why when I access it with no parameter for ID it works, as I get an error says missing parameter for ... but when I actually try to pass a parameters at http://site/admin/images/12 I get a 404 error. What am I missing?

I tried setting the following in my routes, no success either:

Route::any('admin/images', array(
    'as' => 'admin_images',
    'uses' => 'admin.images@index',
));
    //or 
Route::any('admin/images/(:any)', array(
    'as' => 'admin_images',
    'uses' => 'admin.images@index',
));

It seams that my issues with wildcards, 90% happen in my test linux envirnonment (ubuntu). Here's my routes.php that I'm currently using http://pastebin.com/f86A3Usx

Upvotes: 1

Views: 2041

Answers (4)

mavrck
mavrck

Reputation: 1923

Updated Routes:

Route::any('admin/images/(:any?)', array(
    'as' => 'admin_images',
    'uses' => 'admin.images@index',
));

You can simplify your routing by combining your routes for each endpoint. By adding the "?" into your first parameter, this mean that anything can be present, but doesn't have to be. So both /admin/images and /admin/images/1234 are covered.

Updated Controller:

class Admin_Images_Controller extends Admin_Controller
{
    public $restful = true;

    public function __construct()
    {
        parent::__construct();
    }

    public function get_index($id=null)
    {
        echo $id;
    }

    // ...
}

With the addition of "= null" into your method parameter, you can now handle both routes into this function. A simple check of "equals null" within your method should put you well on your way to covering each senario.

Upvotes: 1

Barryvdh
Barryvdh

Reputation: 6579

You should make the $id parameter optional, by passing a default value (like null/false/1)

public function get_index($id = null)
{
    if($id){ 
        echo $id;
    }else{
        echo "No ID given!";
    }   
}

And use (:any?) in your route.

Upvotes: 1

Oddman
Oddman

Reputation: 3959

it could be that you're using the same alias (admin_images) and also, check your order - put the more specific ones first, and more generic as you go down, like so:

Route::any('admin/images/(:any?)', array('uses' => 'admin.images@index'));

Have removed the alias, just for readability.

Upvotes: 2

NARKOZ
NARKOZ

Reputation: 27901

Route::get('admin/images/(:any)', 'admin.images@index');

Upvotes: 1

Related Questions