From f0a1b928dd6dbdf7348bece60ca1ba594df97fa4 Mon Sep 17 00:00:00 2001 From: elvira Date: Tue, 3 Nov 2026 00:09:58 +0200 Subject: [PATCH] Reviews: submit without a redirect, answered with Turbo Streams The review form now submits through Turbo (data-turbo="true"; Drive stays off) and storeReview answers with Turbo Streams instead of a redirect with flashed data: - success: the new review is prepended to the list (same Blade partial as the existing ones), the empty message is removed, the stars/count under the title and the tab label are updated (count and average from the DB, which is what the index builds them from), the form is removed and the thank-you goes into a live region and gets focus - validation error: 422 + a stream that replaces the form with inline errors (aria-invalid/aria-describedby) and the entered values, focus on the first invalid field Nothing on the product page reads the session any more: no session('reviewSubmitted'), old() or $errors, and mergeJustSubmittedReview and the justSubmittedReview flash are gone. searchableSync() stays. Without JS it's a plain POST that redirects back to ?tab=reviews, without inline errors or the thank-you, and the new review shows once Meilisearch catches up. The ?tab=reviews query parameter is noted in the controller as a variant to handle once product pages are cached. New: product/partials/review, product/partials/rating-summary, product/streams/review-stored|review-invalid, and a small focus-on-connect Stimulus controller that only appears on streamed markup. Co-Authored-By: Claude Opus 5.5 --- app/Http/Controllers/ProductController.php | 106 +++++++++--------- .../stimulus/focus-on-connect-controller.js | 17 +++ resources/js/stimulus/index.js | 2 + .../views/components/review-form.blade.php | 72 +++++++++--- .../product/partials/rating-summary.blade.php | 12 ++ .../views/product/partials/review.blade.php | 11 ++ resources/views/product/show.blade.php | 60 +++++----- .../product/streams/review-invalid.blade.php | 8 ++ .../product/streams/review-stored.blade.php | 30 +++++ 9 files changed, 217 insertions(+), 101 deletions(-) create mode 100644 resources/js/stimulus/focus-on-connect-controller.js create mode 100644 resources/views/product/partials/rating-summary.blade.php create mode 100644 resources/views/product/partials/review.blade.php create mode 100644 resources/views/product/streams/review-invalid.blade.php create mode 100644 resources/views/product/streams/review-stored.blade.php diff --git a/app/Http/Controllers/ProductController.php b/app/Http/Controllers/ProductController.php index 5c6492e..4849b1f 100644 --- a/app/Http/Controllers/ProductController.php +++ b/app/Http/Controllers/ProductController.php @@ -46,8 +46,6 @@ public function show(string $locale, int $id) $product = $this->products->getById($id); abort_if($product === null, Response::HTTP_NOT_FOUND); - $product = $this->mergeJustSubmittedReview($product); - [$productOptions, $variantsData] = $this->buildOptionPicker($id); return view('product.show', [ @@ -147,40 +145,6 @@ private function buildOptionPicker(int $productId): array return [$productOptions, $variantsData]; } - /** - * Meilisearch's own write API is itself async — addDocuments() enqueues an - * indexing task and returns immediately, and Laravel\Scout\Engines\ - * MeilisearchEngine::update() never waits on that task, so even - * $product->searchableSync() (which only skips OUR queue) can still land - * the shopper back on this page before Meilisearch has actually processed - * the write. storeReview() flashes the review it just created for exactly - * this one next request; splice it in here rather than trust the index is - * already caught up. Guarded by id so a race the other way — the index - * DID catch up in time — doesn't show the same review twice. - */ - private function mergeJustSubmittedReview(array $product): array - { - $justSubmitted = session('justSubmittedReview'); - - if (! $justSubmitted || (string) ($justSubmitted['product_id'] ?? null) !== (string) $product['id']) { - return $product; - } - - $items = $product['reviews']['items'] ?? []; - - if (collect($items)->contains('id', $justSubmitted['id'])) { - return $product; - } - - $items = [$justSubmitted, ...$items]; - - $product['reviews']['items'] = $items; - $product['reviews']['count'] = count($items); - $product['reviews']['average_rating'] = round(collect($items)->avg('rating'), 1); - - return $product; - } - /** * A storefront-owned, checkout-module-independent stock check — the * product page's "Add to cart" calls this first and only submits to the @@ -214,14 +178,21 @@ public function checkStock(string $locale, Request $request): JsonResponse /** * boboko/core's product_reviews table has no moderation/status column, so * this goes live immediately — no approval queue to land in. + * + * The form submits through Turbo, so the answer is Turbo Streams: the new + * review into the list, the updated count and average, the thank-you in + * place of the form; or, on a validation error, the form again with inline + * errors (422). Nothing goes through the session, so the product page + * itself never reads one (it'll be cached). Without JS this is a plain + * POST that redirects back to the product page, losing the inline errors + * and the thank-you — accepted. + * + * The redirect's ?tab=reviews is a query-string variant of the product + * page: keep that in mind once product pages are cached. */ - public function storeReview(string $locale, Request $request, Product $product): RedirectResponse + public function storeReview(string $locale, Request $request, Product $product): RedirectResponse|Response { - $reviewsUrl = route('product.show', [ - 'locale' => $locale, - 'id' => $product->id, - 'tab' => 'reviews', - ]).'#product-tabs'; + $wantsStream = str_contains((string) $request->header('Accept'), 'text/vnd.turbo-stream.html'); $validator = Validator::make($request->all(), [ 'rating' => ['required', 'integer', 'between:1,5'], @@ -231,7 +202,13 @@ public function storeReview(string $locale, Request $request, Product $product): ]); if ($validator->fails()) { - return redirect($reviewsUrl)->withErrors($validator)->withInput(); + return $wantsStream + ? $this->turboStream('product.streams.review-invalid', [ + 'productId' => $product->id, + 'messages' => $validator->errors(), + 'values' => $request->only('rating', 'content', 'name', 'email'), + ], Response::HTTP_UNPROCESSABLE_ENTITY) + : redirect($this->reviewsUrl($locale, $product)); } $data = $validator->validated(); @@ -251,17 +228,23 @@ public function storeReview(string $locale, Request $request, Product $product): ]); // ReviewServiceProvider also reindexes on the model's `created` event, but - // queued (SCOUT_QUEUE=true) — it wouldn't land before this redirect's page - // load. Syncing here skips our queue too, but Meilisearch's own write API - // is itself async on top of that (see mergeJustSubmittedReview()), so this - // alone still isn't a guarantee — it's the flash below that actually is. + // queued (SCOUT_QUEUE=true). Syncing here skips our queue, so the next + // product page load has it as soon as Meilisearch (itself async) catches + // up. The stream below doesn't wait for the index: it renders the new + // review and the count/average straight from the DB, which is exactly + // what ProductIndexer builds the index's `reviews` from. $product->searchableSync(); - return redirect($reviewsUrl) - ->with('reviewSubmitted', true) - ->with('justSubmittedReview', [ + if (! $wantsStream) { + return redirect($this->reviewsUrl($locale, $product)); + } + + $reviews = ProductReview::where('product_id', $product->id); + + return $this->turboStream('product.streams.review-stored', [ + // Same shape as ProductIndexer::mapReview(), for the shared partial. + 'review' => [ 'id' => $review->id, - 'product_id' => $review->product_id, 'title' => $review->title, 'body' => $review->body, 'rating' => $review->rating, @@ -270,6 +253,25 @@ public function storeReview(string $locale, Request $request, Product $product): 'reply' => null, 'replied_at' => null, 'media' => [], - ]); + ], + 'count' => (clone $reviews)->count(), + 'averageRating' => round((float) (clone $reviews)->avg('rating'), 1), + ]); + } + + private function reviewsUrl(string $locale, Product $product): string + { + return route('product.show', [ + 'locale' => $locale, + 'id' => $product->id, + 'tab' => 'reviews', + ]).'#product-tabs'; + } + + private function turboStream(string $view, array $data, int $status = Response::HTTP_OK): Response + { + return response() + ->view($view, $data, $status) + ->header('Content-Type', 'text/vnd.turbo-stream.html'); } } diff --git a/resources/js/stimulus/focus-on-connect-controller.js b/resources/js/stimulus/focus-on-connect-controller.js new file mode 100644 index 0000000..ccff33e --- /dev/null +++ b/resources/js/stimulus/focus-on-connect-controller.js @@ -0,0 +1,17 @@ +import { Controller } from '@hotwired/stimulus' + +// Moves focus into an element as soon as it lands in the DOM: only rendered +// on markup that arrives through a Turbo Stream (the review form's response), +// never on a normal page load. Focuses the first invalid field if there is +// one (or the first focusable thing inside it, e.g. the rating stars), +// otherwise the element itself (give it tabindex="-1"). +export default class extends Controller { + connect() { + const invalid = this.element.querySelector('[aria-invalid="true"]') + const target = invalid?.matches(FOCUSABLE) ? invalid : invalid?.querySelector(FOCUSABLE) + + ;(target ?? this.element).focus() + } +} + +const FOCUSABLE = 'input:not([type="hidden"]), textarea, select, button, [tabindex]' diff --git a/resources/js/stimulus/index.js b/resources/js/stimulus/index.js index de8ce1c..eac9cd3 100644 --- a/resources/js/stimulus/index.js +++ b/resources/js/stimulus/index.js @@ -10,6 +10,7 @@ import CartCountController from './cart-count-controller' import CarouselController from './carousel-controller' import CustomFieldUploadController from './custom-field-upload-controller' import DropdownController from './dropdown-controller' +import FocusOnConnectController from './focus-on-connect-controller' import FrameScrollController from './frame-scroll-controller' import NavSearchController from './nav-search-controller' import ProductFormController from './product-form-controller' @@ -28,6 +29,7 @@ export function registerControllers(application) { application.register('carousel', CarouselController) application.register('custom-field-upload', CustomFieldUploadController) application.register('dropdown', DropdownController) + application.register('focus-on-connect', FocusOnConnectController) application.register('frame-scroll', FrameScrollController) application.register('nav-search', NavSearchController) application.register('product-form', ProductFormController) diff --git a/resources/views/components/review-form.blade.php b/resources/views/components/review-form.blade.php index 31900a5..3e53107 100644 --- a/resources/views/components/review-form.blade.php +++ b/resources/views/components/review-form.blade.php @@ -1,28 +1,47 @@ -@props(['product']) +{{-- + Review form. Submitted through Turbo (data-turbo="true", Drive stays off + elsewhere): ProductController::storeReview() answers with Turbo Streams. + On a validation error it replaces this form (#product-review-form) with a + copy rendered with `messages` and the entered `values`, and `focus` so + focus-on-connect moves focus to the first invalid field. Never reads the + session (no old() or $errors), so the product page stays cacheable. +--}} +@props([ + 'productId', + 'messages' => null, // Illuminate\Support\MessageBag of validation errors + 'values' => [], + 'focus' => false, +]) -@php $oldRating = (int) old('rating', 0); @endphp +@php + $rating = (int) ($values['rating'] ?? 0); + $error = fn (string $field) => $messages?->first($field); +@endphp
@csrf {{-- Rating --}} - +
- + @for($i = 1; $i <= 5; $i++)