Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 wildcard subdomain + route model binding

Tags:

php

laravel

So when you define a resource controller in a wildcard subdomain group route similar to this:

Route::group(array('domain' => '{subdomain}.example.com'), function() {
  Route::resource('users', 'UserController');
});

on RouteServiceProvider

$router->model('user', 'App\User');

and on the UserController show method:

public function show($user)
{
    return $user;
}

what i get is the subdomain name instead of the user resource. This is because the subdomain parameter is passed to controller methods and i would have to change them like this:

public function show($subdomain, $user)
{
    return $user;
}

I simply don't want to add the subdomain parameter to each and every controller method in my app because i am not going to do anything with it. I use the subdomain parameter in a middleware to do some configuration changes.

How can i do it so the subdomain doesn't get passed to controllers as parameter?

like image 647
Varol Avatar asked Nov 09 '22 15:11

Varol


1 Answers

I'm aware that this question is somewhat old (and potentially stale) although I stumbled across this post when searching for an answer to another route model binding question.

To avoid requiring the subdomain, you can specify that Laravel forgets that route parameter.

You could either do this in a middleware (which checks for the subdomain too), like so:

$request->route()->forgetParameter('subdomain');

Alternatively, using your code snippet, it would look something along the lines of this:

Route::group(array('domain' => '{subdomain}.example.com'), function() {
  Route::forgetParameter('subdomain');
  Route::resource('users', 'UserController');
});

However, I'd strongly recommend that the process is moved into a middleware, as it doesn't feel right putting that in the routes file.

like image 159
Anthony Avatar answered Nov 15 '22 12:11

Anthony