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

Laravel Multi-tenant multi-site setup

Recently I needed to create multi-tenant set up in Laravel. I had an existing site which was running on a url. The client wanted a new site with a separate database with a different url. I could have just cloned the existing site and used it but that would have meant 2 separate code bases. Instead, I decided to have 2 databases and one code base. I found some useful documentation at:

https://medium.com/laravel-4/laravel-4-multisites-26cdc75e4810#.yeqca98z2

  • Set up new site in Nginx
  • Create config folder called construction (the site was running under a url with something like construction.myurl.com
  • Create folders for new site  with bootstrap folder
  • Sym link folders from main site
  • Created database
  • Created a new file bootstrap/environment.php
  • Update bootstrap/start.php
$env = $app->detectEnvironment(function() use($app){

    if(isset($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] == 'construction.myurl.com'){
        return require '/pathtosite/construction/bootstrap/environment.php';
    }

    if(file_exists( __DIR__.'/environment.php')){
        return require __DIR__.'/environment.php';
    }

    return $app->detectEnvironment(array(
        'local' => array('localhost.localdomain','localhost')
    ));

});


Everything worked out fine.

I then created a new config file called config/site.php and config/construction/site.php which contained all the site specific strings that I needed.