The Events and Observers (3) of Laravel have already finished the event model. now let's look at an instance of the model event.
Let's start with a classic example. When registering a new user, we hope to send him a welcome email. This is actually very simple. We only need to open the EventServiceProvider class, and then add the following code after the parent: boot () method:
User::created(function($user){ Mail::send('emails.welcome', ['user' => $user], function($message) use ($user) { $message->to($user->email, $user->first_name . ' ' . $user->last_name)->subject('Welcome to My Awesome App, '.$user->first_name.'!'); }); });
This is done, isn't it very simple?
Note:
Assume that the welcome. blade. php view file already exists in the emails folder under resources/views, and that you have mastered the basic knowledge of sending Laravel emails.
The following is another example of a model event:
We assume that there is a class that sends an email to those who follow the new book published by an author. the class name is NewBookNotifier, the method for sending email notifications is forAuthor ($ authorId), where $ authorId is the author's primary key. We can do this as follows:
Book::created(function($book){ $newBookNotifier = new NewBookNotifier(); $newBookNotifier->forAuthor($book->author->id); });
Done! It is very important that it is very simple. Another important point is that, as we mentioned earlier, no code needs to be changed for the model. You can even add more complex behaviors, but remember not to change any code in the model. The advantage of this is that when you test the model, it will never be interrupted.
We will look at some more complex situations later.