Laravel Classroom image

osdyui
 
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.

 

 

 
 
 

osdyui

Skills    Laravel

Qualifications :-
Location :-,,,
Description:-
Explore
 

  Students (0)