ucha
ucha

Reputation: 373

Custom URL structure for Laravel

I would like to create a custom URL structure for my Laravel application.

Right now I have a structure like this:

  1. mydomain.com/products/product-name - ProductController
  2. mydomain.com/articles/article-name - ArticleController
  3. mydomain.com/users/user-name - UserController

I would like to transform it like this:

  1. mydomain.com/product-name - ProductController
  2. mydomain.com/article-name - ArticleController
  3. mydomain.com/user-name - UserController

I already have slugs in common db table. It's not a problem to detect which controller should I use for "product-name".

I want to know, what's the best practice in this case. Where can I put my logic which connects slug "product-name" to ProductController?

Should I use middleware or is there any other approach to do so?

Upvotes: 1

Views: 561

Answers (1)

Prafulla Kumar Sahu
Prafulla Kumar Sahu

Reputation: 9703

What you want, your can specify that in your web.php like

Route::get('user-{name}', 'UserController@show')->name('users.show');

and in UserController

function show(Request $request, User $name){
    return $name;
}

should work fine, but what about other end points like index, delete, edit etc?

What I feel it will be like

Route::delete('user-{name}', 'UserController@delete')->name('users.delete');

but what about index() ? and even in this case, name must be unique or it will create exceptional results.

May be if you will make it more clear, I may edit my answer according to that, but

I believe, you should follow route-model binding concept of Laravel, in stead of making too much customization. According to route-model binding concept

In your model

public function getRouteKeyName()
{
    return 'name';
}

now, if you want to customize it more, you can use

RouteServiceProvider.php boot() method

public function boot()
{
    parent::boot();
    Route::bind('flat_member', function ($value) {
        return 'user-' . $value;
    });
}

Upvotes: 0

Related Questions