Laravel Nested Resource Group

When I started with Laravel, nested resource group was available. I liked it because I can easily create a beautiful URL with ease. For example, to generate an URL like this/user/1/blog/10, I just need to nest my route with this:

Route::resource('user.blog', 'BlogController');

and my controller will be

class BlogController
{
    public function show(User $user, Blog $blog) 
    {
        //... 
    }
}

Since 5.2, this option is removed from documentation (but still available to use). So I was wondering why and I found someone already spotted this and submit a merge request. However, it was not merged with the reason below given by @taylorotwell.

Interesting…

OK, no problem. I will take his word for it. Since you can archieve something similar with alternative approach, e.g.

Route::post('user/{$user}/blog/{$blog}', 'BlogController@store');
Route::resource('blog', 'BlogController')->except(['store']);

but… I still want to know why it is not a good idea? I want to find out… so I can become a better developer.

Is it because of security? This is the first thing I come of mind. Assuming the URL meant to let user store or view their own blog, e.g. user Alice with user id 1, and she has blog entries 10,11,12. Does it mean if she access URL user/1/25 will be a problem? I don’t think so given if Policy is setup properly.

The other thing I can think of is keeping the route simple. It is because if your model route key name is not its ID but a customized route key name, the URL will be very long. e.g., using the route example above, if the user model route key name is user’s name and the blog model route key name is the blog title, the route will be user/alice/blog/this-is-my-title-of-my-blog. It is definitely longer than blog/this-is-my-title-of-my-blog.

There must be some disadvantage of using nested route, what do you think it is?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.