Practical Implementation of Events in Laravel

1013
events in laravel banner

Laravel is a very powerful framework. It provides many features including Events. Event Listener and Handler is a powerful tool in programming. Particularly, an event is just an occurrence of a particular thing at a particular moment in time.

For example, when a new user is registered, then the confirmation email has to be sent to that particular email of the user. In such cases, Event is very helpful. Event help to optimize the code as it separates application concerns and creates a mechanism for us to hook into actions in our application. One of the most particular reasons to use Event is it helps to maintain the separation of concerns.

You can learn more about Laravel in New Features in Laravel article. Moreover, you can also create your own CRUD application in laravel by following Laravel CRUD Application from scratch article.

Practical Implementation of Event

Implementation of Event is pretty simple. The main is that you need to understand the flow. There are two main terms to understand during Event handler. These are Firing an event and Listening to the Event. You can find more explanation and code snippets at Laravel documentation. In this article, I am implementing the basic usage of Events.

Firing an Event

Firing an Event is easy. This is simply a single line of code.

$response = Event::fire('email.send');

This will fire an Event named email.send. The Fire method returns an array of responses that you can use to control what happens next in your application. After this event is fired, all the rest is handled with Event Handler.

Event can be fired with parameters too. This can be done simply as below.

$email = Event::fire('email.send', array($data));

This will fire an Event with parameter, $data in our case.

Listening to the Event

After the Event is fired, we need to listen to the Event and Handle accordingly. Obviously, it’s not a single line of code. For listening an Event, I have created EventListners.php file inside app folder. In EventListners.php file, we write code to listen the Events fired. Basic structure of Event Listener is as below.

Event::listen(email.send', function($data)
{
    // Handle the event...
});

I have implemented the above code according to my requirements. My EventListeners.php looks like below:

destination_email;
    $source_email = $data->source_email;
    $message = $data->message;
    $response = mail( $destination_email, "Testing Event Handler Form www.vijayrana.com.np", $message, $source_email );
    
    Return $response
});

Here, The Fired Event is listened with Event::listen(’email.send’) and function is used to define additional operation with the event. In above code, I simply grab the destination email, source email and message from parameter $data and used to send to the destination mail provided.

Mail() is just a PHP function to send email. If you are unsure about how this works, you can read this article which is well explained with working code example. After the operation is completed, it returns a response. Then, again the execution process continues in controller.

For this to work, you need to register the Event. it’s a hard question to answer where to register the event because you can register an event almost anywhere! But, here are some tips. Again, like most other bootstrapping code, you may register events in one of your start files such as app/start/global.php. I have register the event in global.php file below the require app_path().’/filters.php’; line. You can also register in App/start/global.php as:

require app_path().'/EventListners.php';

Note: After registering your EventListeners.php file, do no forget to dump-autoload. You can simply run a code composer dump-autoload on your root directory

So, The final codes looks like below:

App/Routes.php

Route::get('laravel-events', array('as' => 'laravel-events', 'uses' => 'HomeController@getLaravelEvents'));
Route::post('laravel-events', 'HomeController@postLaravelEvents');

App/controllers/HomeController.php

 'required|email',
            'source_email'        => 'required|email',
            'message'             => 'required',
        );
        //validate form inputs
        $validator = Validator::make(Input::all(), $rules);

        if($validator->fails()){
            //redirect back if validation fails
            return Redirect::back()->withInput()->withErrors($validator);
        
        }else{
            //get form inputs
            $destination_email = Input::get('destination_email');
            $source_email = Input::get('source_email');
            $message = Input::get('message');
            //create new instance of Feedback model
            $record = new Feedback();
            $record->destination_email = $destination_email;
            $record->source_email = $source_email;
            $record->message = $message;

            if(!$record->save()){
                return Redirect::route('laravel-events')->withInput()->with('error','Sorry, there was some error during registration. Please try again.');
            }

            $data = new stdClass();
            $data->destination_email = $destination_email;
            $data->source_email = $source_email;
            $data->message = $message;    
            //firing an event
            $email = Event::fire('email.send', array($data));
            
            if($email == true){
                Session::flash('success', 'Horraayyy!!!, Email sent successfully using Laravel Event Listener and Handler');
                return Redirect::route('laravel-events');
            }
            elseif($email == false){
                Session::flash('error', 'Oppss!!!, email could not be sent using Laravel Event Listener and Handler. Please Try Again');
                return Redirect::route('laravel-events');
            }
        }
    }
}

App/views/frontend/laravel-events.blade.php

@if(Session::has('success'))
{{ Session::get('success') }}
@elseif(Session::has('error'))
{{ Session::get('error') }}
@endif {{ Form::open( array('class' => '')) }}
{{ Form::label('destination_email','Email which to recieve?', array('class' => '')) }} {{ Form::email('destination_email', '', array('class' => 'form-control')) }}
{{ $errors->first('destination_email') }}
{{ Form::label('source_email', 'Email from which to send?', array('class' => '')) }} {{ Form::email('source_email', '', array('class' => 'form-control')) }}
{{ $errors->first('source_email') }}
{{ Form::label('message', 'Message to Send') }} {{ Form::textarea('message', '', array('class' => 'form-control', 'rows' => '3')) }}
{{ $errors->first('message') }}
{{ Form::reset('Clear', array('class' => 'btn btn-large btn-default')) }} {{ Form::submit('Submit', array('class' => 'btn btn-large btn-success',)) }}
{{ Form::close() }}

App/EventListners.php

destination_email;
    $source_email = $data->source_email;
    $message = $data->message;
    
    $response = mail( $destination_email, "Testing Event Handler Form www.vijayrana.com.np", $message, $source_email );
    
    Return $response
});

That’s it. After it, you are done.

Note: There are also other methods to implement the Events in Laravel. Keep in mind that, it is only a basic demonstration of how Laravel Event is Fired and how it is Listened. You can implement in your own way. Also keep in mind that, for sending email, you need to configure your server.

Read More Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.