find($type, $id, 'view'); $revisions = Revision::query()->where('type', $type)->where('subject_id', $model->getKey())->orderByDesc('id')->limit(100)->get(); return response()->json([ 'revisions' => $revisions->map(fn (Revision $revision, int $position) => [ 'id' => $revision->id, 'created_at' => $revision->created_at, 'user' => $revision->user_name, 'changed' => $revision->changed ?? [], 'current' => $position === 0, // What the changed attributes were then, shortened: enough to see what an old version said. 'values' => collect($revision->changed ?? [])->mapWithKeys(fn (string $key) => [$key => $this->shorten($revision->data[$key] ?? null)])->all(), ])->values(), 'can_restore' => Gate::allows('revisions.restore') && Gate::allows($config['restore']), ]); } public function restore(string $type, string $id, string $revision): JsonResponse { [$config, $model] = $this->find($type, $id, 'restore'); $revision = Revision::query()->where('type', $type)->where('subject_id', $model->getKey())->whereKey($revision)->firstOrFail(); // A post that is on the site is only changed by someone who may publish. abort_if($model instanceof Post && $model->isPublished() && Gate::denies('posts.publish'), 403); app(AuditTrail::class)->about($model); Revisions::restore($model, $revision, $config); return response()->json(['restored' => true]); } /** @return array{0: array{model: class-string, view: string, restore: string, except: list}, 1: Model} */ private function find(string $type, string $id, string $ability): array { $config = Revisions::types()[$type] ?? null; abort_if($config === null, 404); Gate::authorize($config[$ability]); return [$config, $config['model']::query()->findOrFail($id)]; } private function shorten(mixed $value): mixed { $text = is_scalar($value) || $value === null ? (string) $value : json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); return mb_strlen($text) > 300 ? mb_substr($text, 0, 300).'…' : $text; } }