2

I am developing an API through Laravel using Resource Controllers which are linked through the routes.php file. See the example below:

// API routes
Route::group(array('prefix' => 'v1'), function() {

    Route::resource('users', 'UserController');
    Route::resource('users.profile', 'UserProfileController');
    Route::resource('users.tasks', 'UserTaskController');

});

Generally, Laravel does a good job at handling these routes. But there is one exception that I have where I struggle with. My database model is designed to have a one-to-one relationship between the users table and the user_profiles table by looking at the foreign key user_id in the user_profiles table. This means that it is acting on a identifying relationship, so it doesn't have an own primary key, it actually borrows the key of the users table.

Now, I want to update the UserProfile model through the UserProfileController that gets called when the following (example) URL is entered: http://api.projectX.dev:8000/v1/users/{id of the user}/profile. But Laravel forces me to have a URL like this: http://api.projectX.dev:8000/v1/users/{id of the user}/profile/{some other useless ID}.

Is there any way to magically remove that last ID from the resources route and just take advantage of the first ID?

I hope that somebody can help me with this, because finding the answer to this question is actually pretty hard to find right now.

tereško
  • 58,060
  • 25
  • 98
  • 150
Robin
  • 132
  • 7

1 Answers1

1

You're creating a nested resource controller (scroll down a bit). Essentially saying that one resource controller belongs under another resource controller. You can use php artisan routes to see exactly what routes are being generated.

Sounds like you'll need to use a combination of resource controllers and explicitly defined routes to get the exact setup you're after. I don't know enough about how you want to control updating/deleting profiles, or I'd offer something more substantial than that.

Aken Roberts
  • 13,012
  • 3
  • 34
  • 40
  • I have ran the `php artisan routes` command and got the following output (see link): [Click for screenshot](http://tinypic.com/r/246rmts/8) The output shows that I need the call the following URL to update a user's profile: `PUT v1/users/{users}/profile/{profile}`. But I actually don't need the {profile} variable, because the `user_profiles` table doesn't have a own primary key, but only uses a foreign key called `user_id` which points to the `users` table. Is there any way to remove that {profile} parameter from the route without having to create a custom route for it? – Robin Aug 05 '14 at 12:29
  • 2
    No. A resource controller route will automatically create all of those for you. It's best if you create the routes manually for your profile endpoints. – Aken Roberts Aug 05 '14 at 15:11
  • 1
    thanks! I will use your approach to tackle this problem. – Robin Aug 06 '14 at 11:35