大家好~
昨天成功在日曆上新增 Event 了,
今天來對日曆的 Event 做其他操作吧~
Read 的部分我們今天會使用兩種方式:
以下開始我們的實作~
$optParams
的部分我選用了以下四個:
orderBy
singleEvents
false
,若要用 startTime
排序,記得要設成 true
喔~timeMin
timeMax
public function list()
{
$response = $this->googleCalendar->events->listEvents(
$this->calendarId,
[
'orderBy' => 'startTime',
'singleEvents' => true,
'timeMin' => Carbon::today('Asia/Taipei')->toRfc3339String(),
'timeMax' => Carbon::today('Asia/Taipei')->addWeek()->toRfc3339String()
]
);
$collection = collect($response->getItems());
return $collection->map(function ($item) {
return [
'id' => $item->id,
'summary' => $item->summary,
'start' => $item->getStart()->getDateTime(),
'end' => $item->getEnd()->getDateTime(),
];
});
}
測試成功~
public function get($eventId)
{
$eventData = $this->googleCalendar->events->get($this->calendarId, $eventId);
return [
'id' => $eventData->getId(),
'link' => $eventData->getHtmlLink(),
'summary' => $eventData->getSummary(),
'description' => $eventData->getDescription(),
'start' => $eventData->getStart()->getDateTime(),
'end' => $eventData->getEnd()->getDateTime(),
];
}
拿剛剛使用的 Events:list 裡的其中一筆 id,
做單筆 Event 的查詢,
接下來的範例也會以這筆10月9號的 Event 做示範喔~
Event 只會更新在該次請求中有包含的字段,
其他未在該次請求中之字段則保持不變。
public function patch(Request $request, $eventId)
{
$calendarEvent = new Event();
if (isset($request->summary)) {
$calendarEvent->setSummary($request->summary);
}
if (isset($request->description)) {
$calendarEvent->setDescription($request->description);
}
if (isset($request->startTime)) {
$startTime = new EventDateTime();
$startTime->setDateTime($request->startTime);
$calendarEvent->setStart($startTime);
}
if (isset($request->endTime)) {
$endTime = new EventDateTime();
$endTime->setDateTime($request->endTime);
$calendarEvent->setEnd($endTime);
}
$eventPatch = $this->googleCalendar->events->patch(
$this->calendarId,
$eventId,
$calendarEvent
);
return [
'id' => $eventPatch->getId(),
'link' => $eventPatch->getHtmlLink(),
'summary' => $eventPatch->getSummary(),
'description' => $eventPatch->getDescription(),
'start' => $eventPatch->getStart()->getDateTime(),
'end' => $eventPatch->getEnd()->getDateTime(),
];
}
這邊更新的 Event 和剛剛 Events: get 範例用的 Event 是同一個喔,
從上圖可發現 Event 的 summary 更新成功~
public function delete($eventId)
{
$this->googleCalendar->events->delete($this->calendarId, $eventId);
return [
'message' => 'event has been deleted'
];
}
刪除成功~
然後再用 Events:list 確認一下。
可以看到10月9號的 Event 已經不見了。
那麼 Events 的 CRUD 都成功啦~
大家明天見!
若文章有任何問題,
還請大家不吝賜教!