Model Observers Database Transaction (official documentation) #45382
-
On the laravel official documentation, under observers and database transactions, there's this note I don't understand very well: When models are being created within a database transaction, you may want to instruct an observer to only execute its event handlers after the database transaction is committed. You may accomplish this by defining an $afterCommit property on the observer. If a database transaction is not in progress, the event handlers will execute immediately:. As far as the Am I not understanding it clearly here or? On second thought, I think perhaps I get the idea, the statement comes after another that says that the the event handlers are executed after the transaction is commited so I am assuming that the sentence about the transaction not in progress basically talking about after the transaction has been committed and is no longer pending. If what I thought of secondly is correct, I still think it's a bit confusing to mistake it as saying it executes anytime a transaction is not in progress, perhaps if we could make it more obvious like After the transaction has been successfully committed and is no longer in progress, the event handlers will execute immediately. Or remove that statement altogether because it's already mentioned that the handlers execute after a transaction. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
I'm new to Laravel, but not new to software engineering. The point of this hook and the transaction factor seems to be the ability to react when a record is actually been changed/created. If no transaction is in progress, this means that we are in "auto-commit" mode, which wraps every query with a transaction that is automatically committed. So, by specifying |
Beta Was this translation helpful? Give feedback.
I'm new to Laravel, but not new to software engineering. The point of this hook and the transaction factor seems to be the ability to react when a record is actually been changed/created. If no transaction is in progress, this means that we are in "auto-commit" mode, which wraps every query with a transaction that is automatically committed.
So, by specifying
$afterCommit = true
, you are probably saying in Laravel language: "I want this to run only when the change is actually persisted for all users", which happens automatically on every non-transactional query.