, host()
, dan httpHost()
menyediakan fungsi yang berbeza untuk manipulasi URL dan logik khusus domain. Ini amat berharga dalam aplikasi multi-penyewa, permintaan silang domain, dan senario generasi url dinamik. schemeAndHttpHost()
// Accessing host information $domain = $request->host(); // Returns the domain name $hostWithPort = $request->httpHost();// Includes the port if not standard (e.g., :8080) $fullHost = $request->schemeAndHttpHost();// Returns the full scheme and host (e.g., https://example.com)
// app/Services/DomainRouter.php <?php namespace App\Services; use Illuminate\Http\Request; class DomainRouter { public function __construct(private Request $request) {} public function generateUrls(): array { $baseDomain = $this->request->host(); $fullSchemeHost = $this->request->schemeAndHttpHost(); return match ($this->detectEnvironment($baseDomain)) { 'production' => [ 'api' => "{$fullSchemeHost}/api/v1", 'web' => $this->request->httpHost(), 'assets' => str_replace('api', 'cdn', $fullSchemeHost), 'environment' => 'production' ], 'staging' => [ 'api' => "{$fullSchemeHost}/api/v1", 'web' => str_replace('api', 'staging', $this->request->httpHost()), 'assets' => str_replace('api', 'staging-cdn', $fullSchemeHost), 'environment' => 'staging' ], default => [ 'api' => 'http://localhost:8000/api/v1', 'web' => 'http://localhost:3000', 'assets' => 'http://localhost:9000', 'environment' => 'local' ] }; } private function detectEnvironment(string $host): string { if (str_contains($host, 'prod')) { return 'production'; } if (str_contains($host, 'staging')) { return 'staging'; } return 'local'; } }
// Production (api.example.com) { "api": "https://api.example.com/api/v1", "web": "api.example.com", "assets": "https://cdn.example.com", "environment": "production" } // Staging (api.staging.example.com) { "api": "https://api.staging.example.com/api/v1", "web": "staging.example.com", "assets": "https://staging-cdn.example.com", "environment": "staging" }
Atas ialah kandungan terperinci Menguruskan Permintaan Maklumat Hos di Laravel. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!