I just followed a little tutorial on pessimistic locks and I think that it's not for what I'm trying to do.
So perhaps a check-out ?
What would you suggest me ?
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hello,
I have asked ChatGPT for solutions to avoid a user to update a model if another user is already updating it at the same time.
I know that it's possible to lock a model, but it's has also disadvantages, for example if there is a lock on a model and the user never validates the update.
ChatGPT suggests me 3 different ways :
optimistic locking : locking with a simple version field added in the database table
pessimistic locking : locking with lockForUpdate()
check-out : locking with locked_by and locked_at fields added in the database table
The three suggestions are interesting.
The easiest one (I mean with less modifications) to implement seems to be lockForUpdate().
But anyway if a user opens the form to edit a model and doesn't validate it, the model will be locked indefinitely.
Furthermore if I lock a model, it's recommended to use a transaction. How is it possible to use a transaction if I have an edit function and a update function in the controller ? I mean I get the model to be edited in the edit function and then I update the model in the update function in the controller. I don't see how it could be possible to use a transaction straddling 2 different functions.
While writing the post, I think that a check-out is perhaps a nice solution because I don't need any transaction and I can for example set a timeout to solve dead locks.
Can you help me find what could be the best choice to avoid updates conflicts between 2 users ?
Thanks ;).
V
@vincent15000 That is the tricky part.
When you do the load you need to make start the transaction, but that isn't really possible since you don't use the same database session.
In a system that uses persistent connections it's easier since the lock is on the session. But since you are doing it on a request basis, you can't really use the database to handle that for you.
Another option could be to use a table where you add a record when the page is loaded, and then check for that record when loading as another user, and if it is in the table inform user that the record is already used, and is therefor read only.
Please or to participate in this conversation.