简体   繁体   中英

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

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.

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM