fabioselau077's avatar

Problem in Ziggy with Laravel Route::domain and Vue

Hello, I created a new project with laravel + inertia + vue + breeze and ziggy and it will be an e-commerce platform, so each client will have a subdomain and I configured the web.php for this:

Route::domain('{subdomain}.myshop.com')->middleware('verify_shop')->group(function () {
    Route::get('/', [HomePageController::class, 'index']);
	
	// only debug, returning successful subdomain
    Route::get('/debug', function (Request $request) {
        return response()->json([
            'subdomain' => $request->route('subdomain'),
        ]);
    });

    // default route created by breeze
    Route::get('/dashboard', function () {
        return Inertia::render('Dashboard', [
            'title' => 'Dashboard'
        ]);
    })->middleware(['auth', 'verified'])->name('dashboard');

    // default routes auth created by breeze
    Route::middleware('auth')->group(function () {
        Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit');
        Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');
        Route::delete('/profile', [ProfileController::class, 'destroy'])->name('profile.destroy');
    });
});

The problem is that within the application on the frontend in Vue I can't access any route, because as it is within the domain, it is mandatory to pass the 'subdomain' as a parameter in all routes, but I don't want to do this manually, send something like window.location.hostname.split('.')[0] or pass it as a params from the backend to the frontend (Inertia::render) and send it, I wanted to make it more automatic.

Is there any way to improve this? To make the 'subdomain' be sent automatically from the frontend or some other way in Laravel? Because I thought that when I use route::domain it would automatically get the subdomain that is making the request and pass it to the functions within that group.

For example in frontend route('dashboard') return Uncaught Error: Ziggy error: 'subdomain' parameter is required for route 'dashboard'.

0 likes
1 reply
fabioselau077's avatar
fabioselau077
OP
Best Answer
Level 1

Apparently I found a solution. Just set the default URL subdomain in the middleware to the one that Ziggy will use. Following documentarion of ziggy.

For example:

class IdentifyTenant
{
    public function handle(Request $request, Closure $next)
    {
        $subdomain = $request->route('subdomain');

        if (!$subdomain) {
            abort(404, 'Subdomain not found');
        }

        URL::defaults([
            'subdomain' => $subdomain,
        ]);

        return $next($request);
    }
}

Please or to participate in this conversation.