Created
February 25, 2026 07:24
-
-
Save devhammed/1ed1006464c8b054e7e0bf0b43014fa6 to your computer and use it in GitHub Desktop.
Laravel Response Formatter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| declare(strict_types=1); | |
| namespace App\Concerns; | |
| use Closure; | |
| use Inertia\Inertia; | |
| use Inertia\Response; | |
| use InertiaUI\Modal\Modal; | |
| use Illuminate\Http\JsonResponse; | |
| use Illuminate\Http\RedirectResponse; | |
| trait FormatsResponse | |
| { | |
| protected function format(Closure ...$formats): mixed | |
| { | |
| $format = request()->header('HX-Request') | |
| ? 'htmx' | |
| : request()->format(); | |
| abort_unless(isset($formats[$format]), 406); | |
| return $formats[$format](); | |
| } | |
| protected function page(string $component, array $props = [], int $status = 200): JsonResponse|Response | |
| { | |
| return $this->format( | |
| json: fn () => new JsonResponse($props, $status), | |
| html: fn () => Inertia::render($component, $props), | |
| ); | |
| } | |
| protected function modal(string $component, array $props = [], string $baseRoute = 'projects.index', array $baseRouteParams = [], int $status = 200): JsonResponse|Modal | |
| { | |
| return $this->format( | |
| json: fn () => new JsonResponse($props, $status), | |
| html: fn () => Inertia::modal($component, $props)->baseRoute($baseRoute, $baseRouteParams), | |
| ); | |
| } | |
| protected function route(string $route, array $params = [], array $props = [], int $status = 200): JsonResponse|RedirectResponse | |
| { | |
| return $this->format( | |
| json: fn () => new JsonResponse($props, $status), | |
| html: fn () => to_route($route, $params)->flash($props), | |
| ); | |
| } | |
| protected function back(array $props = [], int $status = 200): JsonResponse|RedirectResponse | |
| { | |
| return $this->format( | |
| json: fn () => new JsonResponse($props, $status), | |
| html: fn () => back()->flash($props), | |
| ); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment