My favourite new Laravel 5 feature: Events and event listeners

Laravel 5 has been out for a while now and I’ve had a chance to write some code using all the new features apotheke online cialis. So: what stands out as my favourite feature so far? The answer is events and event listeners

In Laravel 4 you might see some code in the controller like this:

public function processContact(Request $request)
$user = new Student();
$workshop = $event->getWorkshop();
if(!$user->isStudent($Input::get('name'),$event->getRequest()->get('email'))){
    $user->fill($request);
    $user->status = 'C';
    $user->profile = $this->getProfile($request);
    $user->save();
}else {
    $user = $user->getByEmailAndName($event->getRequest()->get('name'),$event->getRequest()->get('email'));
}


if(!$user->isRegistered($user->name,$user->email, $workshop->id)){
    $user->workshops()->attach($workshop->id, ['sign_date'=>date('Y-m-d H:i:s')]);
}
 return $this->getView('contact_done');
}

In Laravel 5, it’s been tidied up so you can do this:

public function processContact(Request $request)
{
    $this->validate($request, [
        'name' =>'required',
        'email' => 'required|email',
        'comments' => 'required'
    ]);

    Event::fire(new ContactEvent($request));

    return $this->getView('contact_done');
}

All the event code in this example has been moved to a ContactListener class

Comments are closed.