0

I'm developing an application where the admin section is accessible via a subdomain like admin.mysite.test.

Everything works fine except sending emails with login credentials for users manually added by the administrator. The email is sent correctly and is visible with services like Mailtrap, but when redirecting after sending, a 404 is generated, and the debugbar reports that the 'admin.users.index' route doesn't exist. It seems like the reference to the subdomain is lost.

If I make the admin area accessible via mysite.test/admin instead of the subdomain, everything works.

I need the list of users entered in 'admin.users.index' to be reloaded after the email has been sent.

Any ideas?

Below is the resource method for inserting into the database.

     /**
     * Store a newly created resource in storage.
     */
    public function store(UserFormRequest $request)
    {
        $user = new User($request->validated());

        if ($file = $request->validated('image')) {

            $path = $this->upload($file, $this->folder, $this->width, $this->height);

            $user->image = $path;

        }

        $save = $user->save();

        if ($save) {

            $user->generated_password = $request->validated('password');

            Mail::to($user->email)->send(new NewUserCreated($user));
            
            return redirect()->route('admin.users.index')->with('success-message', 'Record inserito con successo.');

        } else {

            return back()->withInput()->with('error-message', 'Qualcosa è andato storto.');

        }
    }

route filke is:

use Illuminate\Support\Facades\Route;

Route::middleware('web')->domain('admin.' . env('SITE_URL'))->group( function () {

    Auth::routes();

    Route::group([
        'as' => 'admin.',
        'namespace' => 'App\Http\Controllers\Admin',
        'middleware' => ['auth'],
    ], function () {

        Route::get('dashboard', DashboardController::class)->name('dashboard');

        //other routes...

        Route::resource('users', App\Http\Controllers\Admin\UserController::class)
            ->except(['show']);

    });
});

Route::group([
    'as' => 'front.',
    'namespace' => 'App\Http\Controllers\Front'
], function () {
        
    Route::get('sitemap.xml', SitemapController::class)
        ->name('sitemap.xml');

});

// Localized
Route::localized(function () {

    Route::group([
        'as' => 'front.',
        'namespace' => 'App\Http\Controllers\Front'
    ], function () {

        Route::get(Lang::uri('home'), HomeController::class)
            ->name('home');

        other routes...

    });

});

.env file

APP_NAME="SMV"
APP_ENV=local
APP_DEBUG=true
APP_TIMEZONE=Europe/Rome
APP_URL=http://mysite.test

SITE_URL=mysite.test

APP_LOCALE=it
APP_FALLBACK_LOCALE=it
APP_FAKER_LOCALE=it_IT

APP_MAINTENANCE_DRIVER=file
# APP_MAINTENANCE_STORE=database

PHP_CLI_SERVER_WORKERS=4

BCRYPT_ROUNDS=12

LOG_CHANNEL=stack
LOG_STACK=single
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug

SESSION_DRIVER=file
SESSION_EXPIRE_ON_CLOSE=true
SESSION_LIFETIME=120
SESSION_ENCRYPT=true
SESSION_PATH=/
SESSION_DOMAIN=.mysite.test
SESSION_HTTP_ONLY=true
SESSION_SAME_SITE=null
5
  • how have you defined the admin routes? have you wrapped them with your domain? Commented Jul 28 at 9:16
  • what does dd(redirect()->route('admin.users.index')->getTargetUrl()) show? Commented Jul 29 at 8:35
  • The dd() show admin.mysite.test/users Commented Jul 29 at 14:29
  • so the url is correct? than your error is somewhere else. check if you are redirected again after reaching admin.mysite.test/users Commented Jul 31 at 12:17
  • I would generally have a config for each subdomain I want it redirecting to Commented Aug 6 at 8:50

2 Answers 2

0

From looking at your routes file, the route admin.users.index does not exist, because the names are not defined. You need to update the route as follows:

Route::resource('users', App\Http\Controllers\Admin\UserController::class)
        ->except(['show'])
        ->name('index', 'users.index')
        ->name('destroy', 'users.delete');
Sign up to request clarification or add additional context in comments.

Comments

0

Cause

Laravel uses the current request's host (domain/subdomain) to resolve route names within route() or redirect()->route() helpers. When the application is served under a subdomain (admin.mysite.test), route resolution works as expected as long as the request context remains intact.

In your case, after sending an email using Mail::to()->send(), Laravel performs a redirect:

return redirect()->route('admin.users.index')->with(...);

At this point, Laravel appears to lose the subdomain context, causing it to resolve admin.users.index as if it's on the primary domain (mysite.test). Since this route is defined within a Route::domain('admin.mysite.test') group, Laravel cannot find it under the base domain, hence the 404 error.

This behavior is more likely to occur in development environments (like .test domains) and when certain actions (like sending mail or uploading files) indirectly interfere with the current route context.

Solution

To ensure the redirect targets the correct subdomain and route group, you should instruct Laravel to generate a fully qualified URL explicitly. Use the route() helper with the third parameter set to true to force absolute URL generation:

return redirect()->to(route('admin.users.index', [], true))
    ->with('success-message', 'Record inserito con successo.');

This ensures that the generated URL includes the admin. subdomain regardless of whether Laravel's internal domain context is preserved during the request.

Alternative Solution (Using URL Generator Directly)

You may also use Laravel’s URL generator for more control:

$url = url()->route('admin.users.index', [], true);
return redirect()->to($url)->with('success-message', 'Record inserito con successo.');

This has the same effect: it resolves the named route with its defined domain and prevents fallback to the incorrect base domain.

Important Considerations

1. Route Configuration

Ensure your route is correctly registered under the subdomain group:

Route::middleware('web')->domain('admin.' . env('SITE_URL'))->group(function () {
    Route::resource('users', App\Http\Controllers\Admin\UserController::class)->except(['show']);
});

Also, confirm that SITE_URL is properly set in your .env:

SITE_URL=mysite.test

This would correctly match the domain admin.mysite.test.

2. Session and Cookie Configuration

Your .env configuration includes:

SESSION_DOMAIN=.mysite.test

This is correct. It allows session sharing across subdomains (e.g., admin.mysite.test and mysite.test). However, confirm that cookies are being accepted by your browser for the admin. subdomain and not being blocked due to local development security restrictions.

3. Do Not Change APP_URL for Admin Context

Your APP_URL should remain:

APP_URL=http://mysite.test

Do not change it to admin.mysite.test, as this will affect all URL generations globally. Instead, rely on explicit full URL generation for routes that belong to subdomain groups, as shown earlier.

  1. Use route('admin.users.index', [], true) to force Laravel to generate the full URL with the correct subdomain.

  2. Wrap it within redirect()->to(...) to ensure proper redirection.

  3. Maintain correct route domain groupings and session configuration.

Recommended code:

return redirect()->to(route('admin.users.index', [], true))
    ->with('success-message', 'Record inserito con successo.');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.