Skip to content

Commit d88d431

Browse files
committed
data: Create Data class for inertia share
1 parent 025674b commit d88d431

File tree

2 files changed

+51
-16
lines changed

2 files changed

+51
-16
lines changed

app/Data/InertiaRequestData.php

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
<?php
2+
3+
namespace App\Data;
4+
5+
use Illuminate\Http\Request;
6+
use Illuminate\Support\Facades\Auth;
7+
use Inertia\AlwaysProp;
8+
use Spatie\LaravelData\Data;
9+
use Spatie\TypeScriptTransformer\Attributes\RecordTypeScriptType;
10+
use Spatie\TypeScriptTransformer\Attributes\TypeScript;
11+
use Spatie\TypeScriptTransformer\Attributes\TypeScriptType;
12+
use Tighten\Ziggy\Ziggy;
13+
14+
#[TypeScript]
15+
class InertiaRequestData extends Data
16+
{
17+
public function __construct(
18+
#[RecordTypeScriptType('string', 'string|string[]')]
19+
public AlwaysProp $errors,
20+
21+
public ?UserData $user,
22+
23+
#[TypeScriptType('string[]')]
24+
public \Closure $can,
25+
26+
#[RecordTypeScriptType('string', 'string|string[]')]
27+
public \Closure $ziggy,
28+
29+
public bool $sidebarOpen,
30+
) {}
31+
32+
public static function fromMiddleware(Request $request, AlwaysProp $errors): self
33+
{
34+
return new self(
35+
errors: $errors,
36+
user: Auth::check() ? UserData::from($request->user()) : null,
37+
can: fn () => [
38+
// TODO: Add your permissions here
39+
],
40+
ziggy: fn (): array => [
41+
...(new Ziggy)->toArray(),
42+
'location' => $request->url(),
43+
],
44+
sidebarOpen: ! $request->hasCookie('sidebar_state')
45+
|| $request->cookie('sidebar_state') === 'true',
46+
);
47+
}
48+
}

app/Http/Middleware/HandleInertiaRequests.php

Lines changed: 3 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,9 @@
22

33
namespace App\Http\Middleware;
44

5-
use Illuminate\Foundation\Inspiring;
5+
use App\Data\InertiaRequestData;
66
use Illuminate\Http\Request;
77
use Inertia\Middleware;
8-
use Tighten\Ziggy\Ziggy;
98

109
class HandleInertiaRequests extends Middleware
1110
{
@@ -37,20 +36,8 @@ public function version(Request $request): ?string
3736
*/
3837
public function share(Request $request): array
3938
{
40-
[$message, $author] = str(Inspiring::quotes()->random())->explode('-');
39+
$errors = parent::share($request)['errors'] ?? [];
4140

42-
return [
43-
...parent::share($request),
44-
'name' => config('app.name'),
45-
'quote' => ['message' => trim($message), 'author' => trim($author)],
46-
'auth' => [
47-
'user' => $request->user(),
48-
],
49-
'ziggy' => fn (): array => [
50-
...(new Ziggy)->toArray(),
51-
'location' => $request->url(),
52-
],
53-
'sidebarOpen' => ! $request->hasCookie('sidebar_state') || $request->cookie('sidebar_state') === 'true',
54-
];
41+
return InertiaRequestData::fromMiddleware($request, $errors)->toArray();
5542
}
5643
}

0 commit comments

Comments
 (0)