Many owners of content websites face a situation: users actively read materials but cannot save them for later viewing. The lack of a bookmark system reduces retention and time on site. A simple implementation often leads to duplicates, slow queries, and poor UX. We have implemented dozens of such systems — from basic toggles to complex collections with cross-device synchronization. We offer a proven solution based on a polymorphic relation that works for any entity: articles, products, job listings, videos.
How the polymorphic relation works in the database
The key challenge is to design the database so that you don't create separate tables for each content type. The polymorphic relation solves this with a single bookmarks table:
CREATE TABLE bookmarks ( id SERIAL PRIMARY KEY, user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, bookmarkable_id INTEGER NOT NULL, bookmarkable_type VARCHAR(50) NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), UNIQUE (user_id, bookmarkable_id, bookmarkable_type) ); CREATE INDEX ON bookmarks(user_id, bookmarkable_type, created_at DESC); This approach guarantees uniqueness for each user-entity pair, and the index allows fast retrieval of a user's bookmarks sorted by time. In a real project, we encountered a case where a query without an index took 2 seconds for 10,000 bookmarks — after adding the index, the time dropped to 10 milliseconds. Laravel documentation: Polymorphic relations allow a model to belong to more than one other model on a single association.
Why polymorphic is better than separate tables
| Criterion | Polymorphic | Separate tables |
|---|---|---|
| Number of tables | 1 | N (per content type) |
| Query complexity | One controller | N controllers |
| Extensibility | Add a type — one line | New table + code |
| Performance | One index | N indexes |
Polymorphic reduces code volume by 3–5 times and simplifies maintenance. When a new content type appears (e.g., video), you just add a record in bookmarkable_type — no database migrations.
Step-by-step implementation plan
- Analysis and database design — 0.5 days. Define entity types, create migration.
- Laravel API implementation — 0.5–1 day. Toggle controller, validation, documentation.
- React component creation — 0.5–1 day. Optimistic UI, accessibility.
- Integration and testing — 0.5 days. Unit tests, manual testing.
- Deployment and documentation — 0.5 days. Developer instructions, server deployment.
How the toggle API is implemented in Laravel
The API uses a single endpoint that toggles the bookmark state. We use a controller with toggle and index methods:
class BookmarkController extends Controller { public function toggle(Request $request, string $type, int $id): JsonResponse { $existing = Bookmark::where([ 'user_id' => auth()->id(), 'bookmarkable_type' => $type, 'bookmarkable_id' => $id, ])->first(); if ($existing) { $existing->delete(); return response()->json(['bookmarked' => false]); } Bookmark::create([ 'user_id' => auth()->id(), 'bookmarkable_type' => $type, 'bookmarkable_id' => $id, ]); return response()->json(['bookmarked' => true], 201); } public function index(Request $request): JsonResponse { $bookmarks = Bookmark::where('user_id', auth()->id()) ->when($request->type, fn($q) => $q->where('bookmarkable_type', $request->type)) ->with('bookmarkable') ->latest() ->paginate(20); return response()->json($bookmarks); } } Note: the index method supports filtering by type and pagination — important for the 'My Bookmarks' page. Without with('bookmarkable'), you would get N+1 queries, which is unacceptable at scale.
If you need such a system, order a turnkey implementation.
React component example with optimistic UI
function BookmarkButton({ type, id, initialBookmarked }: BookmarkProps) { const [bookmarked, setBookmarked] = useState(initialBookmarked); const toggle = async () => { setBookmarked(!bookmarked); try { await api.post(`/api/bookmarks/${type}/${id}/toggle`); } catch { setBookmarked(bookmarked); } }; return ( <button onClick={toggle} aria-label={bookmarked ? 'Удалить из закладок' : 'Добавить в закладки'} aria-pressed={bookmarked} className={`bookmark-btn ${bookmarked ? 'bookmark-btn--active' : ''}`} > {bookmarked ? '🔖' : '🏷️'} </button> ); } Optimistic UI: how to avoid delays?
Optimistic update gives feedback in 0 ms, but requires error handling. In a project for an online store, we implemented 5 bookmark buttons on a page — users noted that the site became "fast" after applying this approach. The alternative is pessimistic UI with a loader, but on mobile devices it increases perceived latency by 300–500 ms. Use AbortController to prevent race conditions on rapid clicks.
Process and timeline
| Stage | Duration |
|---|---|
| Analysis and database design | 0.5 day |
| API development (Laravel) | 0.5–1 day |
| React component and integration | 0.5–1 day |
| 'My Bookmarks' page with filtering | 0.5 day |
| Testing and deployment | 0.5 day |
Total: 1 to 2 days for a basic implementation. The timeline may increase if cross-device synchronization or bookmark export is required. In one project, we needed to add WebSocket support for instant synchronization between tabs — this took an additional day.
What's included
- API documentation (OpenAPI/Swagger)
- Source code with comments (Laravel + React)
- Deployment instructions (Docker + CI/CD)
- Warranty of functionality on your hosting
- 2 weeks of post-implementation support
Typical mistakes when implementing bookmarks
- Missing unique constraint — a user can add the same page multiple times, breaking toggle logic.
- Ignoring optimistic UI — a 0.5–1 second delay kills the feeling of responsiveness.
- N+1 query when retrieving
bookmarkable— always usewith(). - Wrong data type for
bookmarkable_type— useVARCHAR(50)with constants to avoid typos.
Get a consultation on implementing bookmarks on your site — we'll evaluate your project in one day and propose the optimal architecture. Contact us to calculate the project cost. Our team has over 5 years of experience in web application development and has completed over 50 projects with bookmark and collection systems.







