Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
Need help with Advanced routing
  • I want to be able to have routes like,

    /users/1/comments/
    /users/1/comments/1/show
    /users/1/comments/1/edit
    /user/1/comments/new

    The user and comment models have a one-to-many relationship. How do I do it?
  • You don't route to models, you route to controller methods.

    Can you be more specific of what you exactly want? Is this what your URL's should look like? And where should they route to?
  • My apologies for the misguided question.

    What I want to say is I have a User model with Users controller with 7 RESTful actions (index, show, edit, create, new, edit, delete). I also have a Comment model with Comments controller with 7 RESTful actions. I want to have the routes for comments embedded under the user route as the example I gave above.

    So if I want to see all the comments made for user with id 1, I go to /users/1/comments , which would be the Comments controller's index action with the user id supplied as a parameter. Likewise, if I want to see one of these comments I would go here, /users/1/comments/1/show . So from what I know in Rails (my apologies again for mentioning Rails in a Fuelphp forum but it's used just for sake of explanation, I understand that it is silly to require a Rails feature in Fuel) you can do the following 

    resources :users do
      resources :comments
    end

    And you would get those routes. Is this possible in Fuel, if so how do I do it? I've bee trying to decipher the routes usage examples for the documentation but I couldn't go beyond the simple routing. Also watched the FuelPHP from Scratch Series video 8 but couldn't find what I am looking for.
     
  • HarroHarro
    Accepted Answer
    You can do that quite easily, but you have to think about how you want the parameters appear in your controller method.

    For /users/1/comments you can use the route
    'users/(:num)/comments' => 'comments/index/$1',
    and in your comments controller use
    public function index($userid = null) { }
    For links like /users/1/comments/new you can use the route
    'users/(:num)/comments/(:any)' => 'comments/index/$2/$1',
    and in your comments controller use
    public function new($userid = null) { }
    For the others, like /users/1/comments/1/show, you can use the route
    'users/(:num)/comments/(:num)/(:any)' => 'comments/$3/$1/$2',
    and in your comments controller use
    public function show($userid = null, $commentid = null) { }
    Define them with the longest one first.
  • Thank you, that worked for me.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion