movie-night-api/app/Http/Resources/MovieListResource.php

57 lines
1.5 KiB
PHP
Raw Normal View History

2026-04-05 00:37:44 -05:00
<?php
namespace App\Http\Resources;
use App\Models\User;
2026-04-05 00:37:44 -05:00
use Auth;
use Illuminate\Database\Eloquent\Collection;
2026-04-05 00:37:44 -05:00
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
/**
* @property int $id
* @property string $name
* @property bool $is_public
* @property int $owner
* @property User $listOwner
* @property Collection $collaborators
* @property Collection $movies
*
* @method string|null getUserRole(int $user_id)
*/
2026-04-05 00:37:44 -05:00
class MovieListResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
$user_id = Auth::id();
return [
'id' => $this->id,
'name' => $this->name,
'is_public' => $this->is_public,
'owner' => $this->listOwner->username,
'role' => $this->getRole($this->owner, $user_id),
'collaborators' => $this->whenLoaded('collaborators', fn () => $this->collaborators->map(fn (User $user) => [
'id' => $user->getKey(),
2026-04-05 00:37:44 -05:00
'username' => $user->username,
'role' => $user->pivot->getAttribute('role_id'),
2026-04-05 00:37:44 -05:00
])),
'movies' => $this->whenLoaded('movies'),
];
}
private function getRole(int $owner_id, int $user_id): ?string
{
if ($owner_id === $user_id) {
return 'OWNER';
2026-04-05 00:37:44 -05:00
}
return $this->getUserRole($user_id);
}
}