diff --git a/src/ResponseFactory.php b/src/ResponseFactory.php index 11d3530d..67d0cfe8 100644 --- a/src/ResponseFactory.php +++ b/src/ResponseFactory.php @@ -4,8 +4,10 @@ use Closure; use Illuminate\Contracts\Support\Arrayable; +use Illuminate\Http\RedirectResponse; use Illuminate\Support\Arr; use Illuminate\Support\Facades\App; +use Illuminate\Support\Facades\Request; use Illuminate\Support\Facades\Response as BaseResponse; use Illuminate\Support\Traits\Macroable; @@ -82,6 +84,10 @@ public function render($component, $props = []) public function location($url) { - return BaseResponse::make('', 409, ['X-Inertia-Location' => $url]); + if (Request::inertia()) { + return BaseResponse::make('', 409, ['X-Inertia-Location' => $url]); + } + + return new RedirectResponse($url); } } diff --git a/tests/ResponseFactoryTest.php b/tests/ResponseFactoryTest.php index 6888d651..297a1602 100644 --- a/tests/ResponseFactoryTest.php +++ b/tests/ResponseFactoryTest.php @@ -2,8 +2,10 @@ namespace Inertia\Tests; +use Illuminate\Http\RedirectResponse; use Illuminate\Http\Response; use Illuminate\Session\Middleware\StartSession; +use Illuminate\Support\Facades\Request; use Illuminate\Support\Facades\Route; use Inertia\Inertia; use Inertia\LazyProp; @@ -22,15 +24,32 @@ public function test_can_macro() $this->assertEquals('bar', $factory->foo()); } - public function test_location_response() + public function test_location_response_for_inertia_requests() { + Request::macro('inertia', function () { + return true; + }); + $response = (new ResponseFactory())->location('https://inertiajs.com'); $this->assertInstanceOf(Response::class, $response); - $this->assertEquals(409, $response->getStatusCode()); + $this->assertEquals(Response::HTTP_CONFLICT, $response->getStatusCode()); $this->assertEquals('https://inertiajs.com', $response->headers->get('X-Inertia-Location')); } + public function test_location_response_for_non_inertia_requests() + { + Request::macro('inertia', function () { + return false; + }); + + $response = (new ResponseFactory())->location('https://inertiajs.com'); + + $this->assertInstanceOf(RedirectResponse::class, $response); + $this->assertEquals(Response::HTTP_FOUND, $response->getStatusCode()); + $this->assertEquals('https://inertiajs.com', $response->headers->get('location')); + } + public function test_the_version_can_be_a_closure() { Route::middleware([StartSession::class, ExampleMiddleware::class])->get('/', function () {