Laravel Resource
У меня есть несколько ресурсов и в основном содержимое ресурса, несколько полей, которые одинаковы для всех других ресурсов, и очень сложно изменить весь ресурс в случае, если мне нужно обновить / добавить ключ / значение в ресурсе.
Есть ли способ, которым я могу создать один основной ресурс, который будет содержать все общие поля, а затем вызвать основной ресурс в моем другом ресурсе и добавить несколько дополнительных полей.
Вот мой контроллер, куда я звоню CitizenFeedResource
файл.
if ($events->total()) {
return CitizenFeedResource::collection($events);
}
Это мое CitizenFeedResource
файл.
use Illuminate\Http\Resources\Json\JsonResource;
class CitizenFeedResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
'description' => $this->description,
'start_timestamp' => optional($this->start_timestamp)->toDateTimeString(),
'end_timestamp' => optional($this->end_timestamp)->toDateTimeString(),
'location' => [
'name' => $this->location,
'landmark' => $this->landmark,
'coordinates' => $this->coordinates,
'city' => $this->city,
],
'open_event' => $this->open_event,
'full_day_event' => $this->full_day_event,
'banner' => $this->banner,
'url' => $this->path(),
'web_url' => $this->webUrl(),
'categories' => $this->categories,
'timestamp' => $this->created_at->toDateTimeString(),
'timestamp_ago' => $this->created_at->diffForHumans(),
'statistics' => $this->statistics,
'additional_details' => $this->additionalDetails(),
'municipal_details' => $this->municipal_details,
'user' => optional($this->user)->getProfile($this->channel, '1.1'),
'complaint_id' => $this->complaint_id,
'volunteers' => (isset($this->volunteers) && $this->volunteers) ? $this->user->getVolunteerProfile($this->volunteers, '1.1') : array(),
'share_count' => (isset($this->statistics) && isset($this->statistics['share_count'])) ? array_sum($this->statistics['share_count']) : 0,
'volunteer_status' => $this->getVolunteerStatus($request),
'editable' => $this->editable(),
'type' => 'Event',
];
}
}
1 ответ
Решение
Вам не нужно расширяться непосредственно из JsonResponse, поэтому вы можете создать один основной объект, скажем так:
use Illuminate\Http\Resources\Json\JsonResource;
class BaseResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
'description' => $this->description,
];
}
}
а потом
class CitizenFeedResource extends BaseResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
$data = parent::toArray($request);
$data['custom_field'] = $this->custom_field;
// ...
return $data;
}
}