55 lines
1.5 KiB
PHP
55 lines
1.5 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Resources;
|
|
|
|
use App\Models\MealPosts;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Http\Resources\Json\JsonResource;
|
|
use Illuminate\Support\Facades\Storage;
|
|
use Illuminate\Support\Str;
|
|
|
|
/** @mixin MealPosts */
|
|
class MealPostsResource extends JsonResource
|
|
{
|
|
public function toArray(Request $request): array
|
|
{
|
|
$user = $this->user;
|
|
|
|
return [
|
|
'id' => $this->id,
|
|
'imageUrl' => $this->imageUrl(),
|
|
'caption' => $this->caption,
|
|
'calories' => $this->calories,
|
|
'proteins' => $this->proteins,
|
|
'carbs' => $this->carbs,
|
|
'fats' => $this->fats,
|
|
'title' => $this->title,
|
|
'visibility' => $this->visibility,
|
|
'type' => $this->type,
|
|
'eatenAt' => $this->eaten_at,
|
|
'createdAt' => $this->created_at,
|
|
'updatedAt' => $this->updated_at,
|
|
'ingredients' => MealPostIngredientsResource::collection($this->whenLoaded('ingredients')),
|
|
|
|
'user' => [
|
|
'name' => $user?->name,
|
|
'avatarUrl' => $user?->avatar_url ? asset(Storage::url($user->avatar_url)) : null,
|
|
'id' => $user->id,
|
|
],
|
|
];
|
|
}
|
|
|
|
private function imageUrl(): ?string
|
|
{
|
|
if (! $this->image_url) {
|
|
return null;
|
|
}
|
|
|
|
if (Str::startsWith($this->image_url, ['http://', 'https://'])) {
|
|
return $this->image_url;
|
|
}
|
|
|
|
return asset(Storage::url($this->image_url));
|
|
}
|
|
}
|