Alternative for route() when using path identification
Description & Why this should be added
Currently when you want to use the route() function in combination with the path identification method of identifying tenants. You are required to supply the tenant parameter each time you use the route() function.
For example:
route('my-route-name', ['tenant' => tenant(), 'my-app-param' => 'foo'])
Ideally I'd want to use something like:
tenant_path_route('my-route-name', ['my-app-param' => 'foo'])
A possible solution to this issue is to add this as a helper. With this helper you can then easily replace all your route() calls to the new helper function, without having to change parameters.
Perhaps setting URL defaults would be a better option?
there is tenant_route() in the helpers, but I see that it still requires domain as the first method argument. @stancl do you have any thoughts on this? I really want to contribute to this amazing package
I found this issue and solved it like @ragulka mentioned.
app/Http/Middelware/SetDefaultTenantForUrls.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\URL;
class SetDefaultTenantForUrls
{
/**
* Handle the incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return \Illuminate\Http\Response
*/
public function handle($request, Closure $next)
{
URL::defaults(['tenant' => tenant()->id]);
return $next($request);
}
}
app/Http/Kernel.php
Added to protected $routeMiddleware at the bottom
'tenant' => \App\Http\Middleware\SetDefaultTenantForUrls::class,
routes/web.php Relevant code to make this middleware work:
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ImportController;
use Stancl\Tenancy\Middleware\InitializeTenancyByPath;
use App\Http\Middleware\SetDefaultTenantForUrls;
Route::get('/', function () {
return view('public_home');
});
Route::group([
'prefix' => '/app/{tenant}',
'middleware' => [InitializeTenancyByPath::class, SetDefaultTenantForUrls::class],
], function () {
Route::get('/', function () {
return view('welcome');
});
require __DIR__ . '/auth.php';
});
I have added this function on my helpers
if (! function_exists('tenant_route')) {
function tenant_route($route, $parameters = [])
{
if (! array_key_exists(PathTenantResolver::$tenantParameterName, $parameters)) {
$parameters[PathTenantResolver::$tenantParameterName] = optional(tenant())->getTenantKey();
}
return route($route, $parameters);
}
}