diff --git a/app/Http/Controllers/V1/User/TicketController.php b/app/Http/Controllers/V1/User/TicketController.php index 8b41e86..1cc2e72 100644 --- a/app/Http/Controllers/V1/User/TicketController.php +++ b/app/Http/Controllers/V1/User/TicketController.php @@ -22,25 +22,20 @@ class TicketController extends Controller if ($request->input('id')) { $ticket = Ticket::where('id', $request->input('id')) ->where('user_id', $request->user['id']) - ->first(); + ->first() + ->load('message'); if (!$ticket) { return $this->fail([400, __('Ticket does not exist')]); } $ticket['message'] = TicketMessage::where('ticket_id', $ticket->id)->get(); - for ($i = 0; $i < count($ticket['message']); $i++) { - if ($ticket['message'][$i]['user_id'] == $ticket->user_id) { - $ticket['message'][$i]['is_me'] = true; - } else { - $ticket['message'][$i]['is_me'] = false; - } - } - return $this->success($ticket); + $ticket['message']->each(function ($message) use ($ticket) { + $message['is_me'] = ($message['user_id'] == $ticket->user_id); + }); + return $this->success(TicketResource::make($ticket)->additional(['message' => true])); } $ticket = Ticket::where('user_id', $request->user['id']) ->orderBy('created_at', 'DESC') ->get(); - - return $this->success(TicketResource::collection($ticket)); } diff --git a/app/Http/Resources/MessageResource.php b/app/Http/Resources/MessageResource.php new file mode 100644 index 0000000..f3992c6 --- /dev/null +++ b/app/Http/Resources/MessageResource.php @@ -0,0 +1,26 @@ + + */ + public function toArray(Request $request): array + { + return [ + "id" => $this['id'], + "ticket_id" => $this['ticket_id'], + "is_me" => $this['is_me'], + "message" => $this["message"], + "created_at" => $this['created_at'], + "updated_at" => $this['updated_at'] + ]; + } +} diff --git a/app/Http/Resources/TicketResource.php b/app/Http/Resources/TicketResource.php index 603cfab..9b9a773 100644 --- a/app/Http/Resources/TicketResource.php +++ b/app/Http/Resources/TicketResource.php @@ -13,13 +13,14 @@ class TicketResource extends JsonResource * @return array */ public function toArray(Request $request): array - { + { $data = [ "id" => $this['id'], "level" => $this['level'], "reply_status" => $this['reply_status'], "status" => $this['status'], "subject" => $this['subject'], + "message" => array_key_exists('message',$this->additional) ? MessageResource::collection($this['message']) : null, "created_at" => $this['created_at'], "updated_at" => $this['updated_at'] ]; diff --git a/app/Models/Ticket.php b/app/Models/Ticket.php index cd26663..ff098e4 100644 --- a/app/Models/Ticket.php +++ b/app/Models/Ticket.php @@ -13,4 +13,10 @@ class Ticket extends Model 'created_at' => 'timestamp', 'updated_at' => 'timestamp' ]; + + + public function message() + { + return $this->hasMany(TicketMessage::class, 'ticket_id', 'id'); + } }