Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 - what's the difference for creating and created model events?

Tags:

laravel

Sorry I am new to Laravel and confused a little bit about the difference of creating and created model events. I found in laravel docs:

Eloquent models fire several events, allowing you to hook into various points in the model's lifecycle using the following methods: creating, created, updating, updated, saving, saved, deleting, deleted, restoring, restored...Whenever a new model is saved for the first time, the creating and created events will fire.

But what's the difference of creating and created events? Will creating and created events always be fired together? Or is there a situation when creating is fired but created is not?

like image 866
Woodrow Norris Avatar asked Mar 13 '23 18:03

Woodrow Norris


1 Answers

The main difference (at least for me) is that:

  • The creating event is more "powerful" because as the example of the docs states, you're able to cancel the creation of a model during the creating event, if, for example, it's not valid.

  • On the other hand, the created event will be fired when the model is already saved to the database so you're not able to cancel anything, you only could prepare other data, for example, once the model is saved.

A possible case when one event is fired, but not the other: in the example of the docs, if the model is not valid, the creating event will be fired, but not the created event as it's not valid, and it won't be saved to the database.

Greetings!

like image 77
soutoner Avatar answered Apr 28 '23 08:04

soutoner