diff --git a/src/ResponseFactory.php b/src/ResponseFactory.php index 125667e9..b88c497c 100644 --- a/src/ResponseFactory.php +++ b/src/ResponseFactory.php @@ -104,6 +104,24 @@ public function render(string $component, $props = []): Response ); } + + /** + * @param array|Arrayable $props + * @param array $customProps + * @return JsonResponse|Response + */ + public function response($component, $props = [], $customProps = []) + { + $props = array_merge($props, $customProps); + + if (request()->header('Accept') === 'application/json') { + return response()->json($props); + } + + return $this->render($component, $props); + } + + /** * @param string|SymfonyRedirect $url */ diff --git a/tests/ResponseFactoryTest.php b/tests/ResponseFactoryTest.php index 94cdf798..0a22f845 100644 --- a/tests/ResponseFactoryTest.php +++ b/tests/ResponseFactoryTest.php @@ -16,6 +16,7 @@ use Illuminate\Contracts\Support\Arrayable; use Illuminate\Http\Request as HttpRequest; use Illuminate\Session\Middleware\StartSession; +use Inertia\Testing\AssertableInertia as Assert; class ResponseFactoryTest extends TestCase { @@ -143,6 +144,25 @@ public function test_shared_data_can_be_shared_from_anywhere(): void ]); } + + /** + * @test + */ + public function test_can_respond_with_a_response_or_json_based_on_accept_header() + { + Route::get('/', function () { + return Inertia::response('User/Edit', ['props' => ['foo' => 'bar']]); + }); + + $response = $this->get('/', ['Accept' => 'application/json']); + $response->assertJson(['props' => ['foo' => 'bar']]); + + // Without the Accept header, it defaults to Inertia Component + $this->get('/')->assertInertia(function (Assert $page) { + $page->component('User/Edit'); + }); + } + public function test_can_flush_shared_data(): void { Inertia::share('foo', 'bar');