migrant-web/app/Http/Middleware/HandleInertiaRequests.php
2026-05-20 13:26:43 +05:30

93 lines
2.9 KiB
PHP

<?php
namespace App\Http\Middleware;
use Illuminate\Http\Request;
use Inertia\Middleware;
class HandleInertiaRequests extends Middleware
{
/**
* The root template that's loaded on the first page visit.
*
* @see https://inertiajs.com/server-side-setup#root-template
*
* @var string
*/
protected $rootView = 'app';
/**
* Determines the current asset version.
*
* @see https://inertiajs.com/asset-versioning
*/
public function version(Request $request): ?string
{
return parent::version($request);
}
/**
* Define the props that are shared by default.
*
* @see https://inertiajs.com/shared-data
*
* @return array<string, mixed>
*/
public function share(Request $request): array
{
$sess = session('user');
$userId = is_array($sess) ? ($sess['id'] ?? null) : ($sess->id ?? null);
$user = $userId ? \App\Models\User::find($userId) : \App\Models\User::where('role', 'employer')->first();
$userData = null;
$unreadCount = 0;
if ($user) {
$sub = \Illuminate\Support\Facades\DB::table('subscriptions')
->where('user_id', $user->id)
->where('status', 'active')
->latest('id')
->first();
$profile = \Illuminate\Support\Facades\DB::table('employer_profiles')
->where('user_id', $user->id)
->first();
$unreadCount = \Illuminate\Support\Facades\DB::table('messages')
->join('conversations', 'messages.conversation_id', '=', 'conversations.id')
->where('conversations.employer_id', $user->id)
->where('messages.sender_type', 'worker')
->whereNull('messages.read_at')
->count();
$userData = [
'id' => $user->id,
'name' => $user->name,
'email' => $user->email,
'role' => $user->role,
'company_name' => $profile ? $profile->company_name : 'Al Mansoor Household',
'subscription_status' => $sub ? 'active' : 'none',
'subscription_expires_at' => $sub && $sub->expires_at ? date('M d', strtotime($sub->expires_at)) : null,
];
// Sync with session so that controllers have access to the exact user
session(['user' => (object) $userData]);
}
return [
...parent::share($request),
'auth' => [
'user' => $userData,
],
'unread_messages_count' => $unreadCount,
'flash' => [
'status' => session('status'),
'reason' => session('reason'),
'success' => session('success'),
'error' => session('error'),
'first_login' => session('first_login'),
],
];
}
}