Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Addition of Inertia::response to handle both json and component #664

Open
wants to merge 5 commits into
base: 1.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions src/ResponseFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
*/
Expand Down
20 changes: 20 additions & 0 deletions tests/ResponseFactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down Expand Up @@ -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');
Expand Down
Loading