Laravel's Events and Observers (3)

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.