Laravel Classroom image

Anil  Bist / Professional / Web Technology

 
To post your Question Join Classroom
 
Lesson Topics's No:-  First|1 | 2 | 3 | 4 | 5|
Lessons:-Events

12.5 Example Usage
So where will using Events come in handy? Well imagine we have a simple task management
application. These types of applications will likely have a User type object to allow our users to
login and use the application. User objects can also be created to add more users to the system.
Let’s attach a Laravel Event to the user creation process..
1 <?php
2
3 $new_user = array(.. user details here ..);
4 $u = new User($new_user);
5 $u->save();
6
7 Event::fire('myapp.new_user', array($u->id));As you can see, we pass the new user’s id value to the ‘myapp.new_user’ event so that all event
listeners are aware of which user has been created.
Now let’s create an extension to our application. The extension should not interfere with the
existing code of the application, it could be an extra library, or a bundle, anything outside of the
main application.
In our extension we are going to add a prefix to the users name (this is somehow useful to our
extension). Let’s do this by listening to the user event.
1 <?php
2
3 Event::listen('myapp.new_user', function ($uid) {
4 $user = User::find($uid);
5 $user->name = 'Myapp_'.$user->name;
6 $user->save();
7 });
We create a listener that receives the user id. Using this we can retrieve the new user from the
database and apply the changes.
We have now added some extra functionality to the application without editing its core files. It
is the responsibility of the application’s author to insert Event triggers or fire() methods within
area’s of the application that are likely to be extended. Without these events the application’s
source would have to be modified.

 

 

 
 
 
image
Anil  Bist

Skills    Laravel

Qualifications :- High School - SLV, College/University - Graphic Era Deemed Univ University,
Location :-Dehradun,Dehradun,Uttarakhand,India
Description:-

I started my Professional Journey in 2006 with one of the Web Development Company in Bangalore and my 1st framework was "Ruby on Rail" as Web development and delivered around 5+ Projects using this platform. Then came another dimension as JEE/Sturst framework, Gradually I realized that I want to build something on my own and give my passion and energy on creating something different a
Explore

 

  Students (0)