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:
elviraandClaude Opus 5.5 committed 2026-11-03 00:09:58 +02:00
1 parent c1acc0067c
commit f0a1b928dd
9 files changed
+217 -101

No files matched your search

+54 -52
View File
@@ -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');
}
}
@@ -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]'
+2
View File
@@ -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)
@@ -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
<form
id="product-review-form"
method="POST"
action="{{ route('product.reviews.store', ['locale' => app()->getLocale(), 'product' => $product['id']]) }}"
action="{{ route('product.reviews.store', ['locale' => app()->getLocale(), 'product' => $productId]) }}"
class="flex flex-col gap-8 mt-10"
data-controller="star-rating"
data-star-rating-rating-value="{{ $oldRating }}"
data-turbo="true"
data-controller="star-rating{{ $focus ? ' focus-on-connect' : '' }}"
data-star-rating-rating-value="{{ $rating }}"
data-action="submit->star-rating#validate"
>
@csrf
{{-- Rating --}}
<x-ui.field :label="__('storefront.review.rating')" for="rating" :required="true" :error="$errors->first('rating')">
<x-ui.field :label="__('storefront.review.rating')" for="rating" :required="true" :error="$error('rating')">
<div
id="rating"
class="flex items-center gap-1.5 text-brand"
role="radiogroup"
aria-label="{{ __('storefront.review.rating') }}"
aria-required="true"
aria-describedby="rating-client-error"
aria-describedby="rating-client-error{{ $error('rating') ? ' rating-error' : '' }}"
@if ($error('rating')) aria-invalid="true" @endif
>
<input type="hidden" name="rating" value="{{ $oldRating }}" data-star-rating-target="input">
<input type="hidden" name="rating" value="{{ $rating }}" data-star-rating-target="input">
@for($i = 1; $i <= 5; $i++)
<button
type="button"
@@ -30,7 +49,7 @@ class="flex items-center gap-1.5 text-brand"
data-value="{{ $i }}"
data-action="click->star-rating#select mouseenter->star-rating#hover mouseleave->star-rating#leave"
aria-label="{{ trans_choice('storefront.review.stars_count', $i, ['count' => $i]) }}"
aria-pressed="{{ $i === $oldRating ? 'true' : 'false' }}"
aria-pressed="{{ $i === $rating ? 'true' : 'false' }}"
>
<svg
xmlns="http://www.w3.org/2000/svg"
@@ -49,16 +68,39 @@ class="w-6 h-6"
<p id="rating-client-error" data-star-rating-target="error" class="text-sm text-red-600" role="alert" hidden>{{ __('storefront.review.rating_required') }}</p>
</x-ui.field>
<x-ui.field :label="__('storefront.review.write_label')" for="review-content" :required="true" :error="$errors->first('content')">
<x-ui.textarea id="review-content" name="content" :required="true" :rows="6">{{ old('content') }}</x-ui.textarea>
<x-ui.field :label="__('storefront.review.write_label')" for="review-content" :required="true" :error="$error('content')">
<x-ui.textarea
id="review-content"
name="content"
:required="true"
:rows="6"
:aria-invalid="$error('content') ? 'true' : null"
:aria-describedby="$error('content') ? 'review-content-error' : null"
>{{ $values['content'] ?? '' }}</x-ui.textarea>
</x-ui.field>
<x-ui.field :label="__('storefront.review.name')" for="review-name" :labelDescription="__('storefront.review.name_optional')" :error="$errors->first('name')">
<x-ui.input id="review-name" name="name" autocomplete="name" :value="old('name')" />
<x-ui.field :label="__('storefront.review.name')" for="review-name" :labelDescription="__('storefront.review.name_optional')" :error="$error('name')">
<x-ui.input
id="review-name"
name="name"
autocomplete="name"
:value="$values['name'] ?? null"
:aria-invalid="$error('name') ? 'true' : null"
:aria-describedby="$error('name') ? 'review-name-error' : null"
/>
</x-ui.field>
<x-ui.field :label="__('storefront.review.email')" for="review-email" :required="true" :labelDescription="__('storefront.review.email_not_published')" :error="$errors->first('email')">
<x-ui.input id="review-email" name="email" type="email" :required="true" autocomplete="email" :value="old('email')" />
<x-ui.field :label="__('storefront.review.email')" for="review-email" :required="true" :labelDescription="__('storefront.review.email_not_published')" :error="$error('email')">
<x-ui.input
id="review-email"
name="email"
type="email"
:required="true"
autocomplete="email"
:value="$values['email'] ?? null"
:aria-invalid="$error('email') ? 'true' : null"
:aria-describedby="$error('email') ? 'review-email-error' : null"
/>
</x-ui.field>
<div>
@@ -0,0 +1,12 @@
{{-- Average stars + review count under the product title. Shared by the
product page and the review-stored Turbo Stream (#product-rating-summary). --}}
<x-reviews-stars
id="product-rating-summary"
:rating="$rating ?? 0"
:count="$count"
:showCount="true"
:linkable="true"
data-controller="tab-link"
data-tab-link-tabs-outlet="#product-tabs"
data-tab-link-panel-value="reviews"
/>
@@ -0,0 +1,11 @@
{{-- One review, from its index-shaped array (ProductIndexer::mapReview()).
Shared by the product page's list and the review-stored Turbo Stream. --}}
<x-review-card :review="[
'rating' => $review['rating'],
'name' => $review['reviewer_name'],
'date' => $review['reviewed_at'] ? \Illuminate\Support\Carbon::createFromTimestamp($review['reviewed_at'])->translatedFormat('d M Y') : '',
'text' => $review['body'],
'image' => $review['media'][0]['url'] ?? null,
'reply' => $review['reply'] ?? null,
'replyDate' => ($review['replied_at'] ?? null) ? \Illuminate\Support\Carbon::createFromTimestamp($review['replied_at'])->translatedFormat('d M Y') : null,
]" />
+26 -34
View File
@@ -154,15 +154,10 @@ class="absolute bottom-8 left-1/2 -translate-x-1/2 text-white text-sm lg:left-au
{{ $product['name'] }}
</h1>
<x-reviews-stars
:rating="$product['reviews']['average_rating'] ?? 0"
:count="$product['reviews']['count']"
:showCount="true"
:linkable="true"
data-controller="tab-link"
data-tab-link-tabs-outlet="#product-tabs"
data-tab-link-panel-value="reviews"
/>
@include('product.partials.rating-summary', [
'rating' => $product['reviews']['average_rating'],
'count' => $product['reviews']['count'],
])
@if($product['price'] !== null)
<p class="text-2xl font-bold" data-product-form-target="price">
@@ -237,34 +232,31 @@ class="flex flex-col gap-6"
</div>
</x-slot>
<x-slot name="reviews">
@if(session('reviewSubmitted'))
<p class="mb-8 text-sm font-semibold" role="status">{{ __('storefront.review.thank_you') }}</p>
{{-- Stream targets for ProductController::storeReview(): the new
review is prepended to #product-reviews-list, the empty
message and #product-review-section removed, and the thank-you
put in the #product-review-status live region. The list hides
itself while it has no reviews. --}}
<div id="product-review-status" role="status"></div>
<div id="product-reviews-list" class="mb-10 [&:not(:has(>*))]:hidden">
@foreach($product['reviews']['items'] ?? [] as $review)
@include('product.partials.review', ['review' => $review])
@endforeach
</div>
@if(empty($product['reviews']['items']))
<p id="product-reviews-empty" class="text-neutral-500 mb-10">{{ __('storefront.review.no_reviews_yet') }}</p>
@endif
@if(!empty($product['reviews']['items']))
<div class="mb-10">
@foreach($product['reviews']['items'] as $review)
<x-review-card :review="[
'rating' => $review['rating'],
'name' => $review['reviewer_name'],
'date' => $review['reviewed_at'] ? \Illuminate\Support\Carbon::createFromTimestamp($review['reviewed_at'])->translatedFormat('d M Y') : '',
'text' => $review['body'],
'image' => $review['media'][0]['url'] ?? null,
'reply' => $review['reply'] ?? null,
'replyDate' => $review['replied_at'] ? \Illuminate\Support\Carbon::createFromTimestamp($review['replied_at'])->translatedFormat('d M Y') : null,
]" />
@endforeach
</div>
@else
<p class="text-neutral-500 mb-10">{{ __('storefront.review.no_reviews_yet') }}</p>
@endif
<div id="product-review-section">
<h3 class="text-h4 font-bold">
{{ $product['reviews']['count'] > 0 ? __('storefront.review.write_new') : __('storefront.review.write_first') }}
{{ __('storefront.review.for_product', ['name' => $product['name']]) }}
</h3>
<h3 class="text-h4 font-bold">
{{ $product['reviews']['count'] > 0 ? __('storefront.review.write_new') : __('storefront.review.write_first') }}
{{ __('storefront.review.for_product', ['name' => $product['name']]) }}
</h3>
<x-review-form :product="$product" />
<x-review-form :product-id="$product['id']" />
</div>
</x-slot>
</x-ui.tabs>
@@ -0,0 +1,8 @@
{{-- Turbo Stream answer to a review that failed validation
(ProductController::storeReview(), status 422): the form again, with
inline errors and the entered values, focus on the first invalid field. --}}
<turbo-stream action="replace" target="product-review-form">
<template>
<x-review-form :product-id="$productId" :messages="$messages" :values="$values" :focus="true" />
</template>
</turbo-stream>
@@ -0,0 +1,30 @@
{{-- Turbo Stream answer to a successful review submission
(ProductController::storeReview()). Targets live in product/show.blade.php. --}}
<turbo-stream action="prepend" target="product-reviews-list">
<template>
@include('product.partials.review', ['review' => $review])
</template>
</turbo-stream>
<turbo-stream action="remove" target="product-reviews-empty"></turbo-stream>
<turbo-stream action="replace" target="product-rating-summary">
<template>
@include('product.partials.rating-summary', ['rating' => $averageRating, 'count' => $count])
</template>
</turbo-stream>
<turbo-stream action="update" target="tab-btn-reviews">
<template>{{ __('storefront.product.reviews') . ' (' . $count . ')' }}</template>
</turbo-stream>
<turbo-stream action="remove" target="product-review-section"></turbo-stream>
{{-- Into the live region that's already on the page, so it's announced;
focus moves to it too, since the form (and the focused submit button)
just went away. --}}
<turbo-stream action="update" target="product-review-status">
<template>
<p class="mb-8 text-sm font-semibold" tabindex="-1" data-controller="focus-on-connect">{{ __('storefront.review.thank_you') }}</p>
</template>
</turbo-stream>