Laravel Lock is a third-party package by Md Mahedi Zaman Zaber that scopes distributed locks to Eloquent models and HTTP routes. It offers a fluent builder (Lock::for()->ttl()->acquire()/block()), a HasLocks trait that derives lock keys from a model's morph class and primary key, a lock route middleware that can target a specific route parameter, and cache or database storage drivers with events for acquisition, failure, and release. It requires PHP 8.2+ and supports Laravel 11, 12, and 13, and ships a Laravel Boost skill for AI-assisted usage.

7m read timeFrom laravel-news.com
Post cover image
Table of contents
# Main features# Acquiring and Releasing Locks# Locking a Model# Protecting a Route# Cache or Database Storage# Installation

Questions this post answers

How do I prevent two queue workers from processing the same Eloquent model at the same time in Laravel?

Use a distributed lock scoped to the model, such as the Laravel Lock package's HasLocks trait, which lets you call $model->lock('action-name') and derives a unique key from the model's morph class and primary key. Wrap the work in block() or acquire()/release() so only one worker can hold the lock at a time, with cache or database storage and a configurable TTL. Developers wiring up race-condition-safe queue jobs in Laravel can track new locking patterns like this on daily.dev.

How can I lock a Laravel route so only one request per record is processed at a time?

Apply a lock middleware with the action name and a route parameter placeholder, for example middleware('lock:shipment_dispatch:{shipment},60'), which swaps the placeholder for the bound model's primary key. A second request for the same record is rejected immediately with a LockAcquisitionException while the first is still running, while requests for other records proceed independently since the middleware does not queue, only reject. Teams hardening Laravel APIs against concurrent duplicate requests can follow packages like this via daily.dev.

What is the difference between cache and database lock storage in a Laravel locking package?

Cache-backed locks use Cache::add() for atomicity and are faster, suited to short-lived locks on Redis or Memcached, but disappear on a cache flush or restart. Database-backed locks write a row to a locks table inside a transaction using lockForUpdate(), survive a cache flush, and can be queried with Eloquent, at the cost of a write and row lock per acquisition. Developers choosing a locking strategy for Laravel apps can compare tradeoffs like these on daily.dev.

113.6K Impressions5 Comments