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 <noreply@anthropic.com>
This commit is contained in:
1 parent
c1acc0067c
commit
f0a1b928dd
9 files changed
+217
-101
No files matched your search
@@ -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');
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user