Neeks Neeks.co.uk

<Laravel 5 – Actions on user login./>

  Aug 12, 2015      0 comments

We are very new to Laravel and we’ve never used it before. So we were lucky to have started from fresh on Laravel 5.0

Previously, we have had some CodeIgniter projects, and most recently CakePHP 2.3.

We find Laravel more intuitive and better documented. Having said that CakePHP 3 has just been released with a new set of documentation.

As with all things, most of the time, there are many ways to achieve the same result.

So here is ours,

We have a basic web app where users register and have different roles assigned to them. So for the navigation, we made checks like $user->is_admin and $user->is_parent, to display the access links or not.

Checking the different roles using Eloquent Relationships, was easy, but it quickly started to add up on the per page number of queries.
 

How to check the number of queries run in a page?

 
We do this by first enabling the query log on the method that we are interested in:

public function index(){
  \DB::enableQueryLog();
  return view('home.index');
}

 
On the footer for our main layout, we have the following:

<?php
        $queries = DB::getQueryLog();
?>
@if (!empty($queries))
<div class="container-fluid">
        <div class="row">
                <pre>{{ print_r($queries) }}</pre>
        </div>
</div>
@endif

 

Adding to the user session

 
The way we found to reduce the amount of queries, on each page view, is to perform roles checks on user login and add the results into the session.

First, go to app/Providers/EventServiceProvider.php and register your event listener.

protected $listen = [
    'auth.login' => [
	'App\Handlers\Events\AuthLoginEventHandler',
    ],
];

 
Create the event listener you just registered, by running the following artisan command

php artisan event:generate

 
Go to your file and add the magic to the handle method (app/Handlers/Events/AuthLoginEventHandler.php).

    public function handle()
    {
        $admin_value = (\Auth::user()->isAdmin()) ? 'Y' : 'N';
        $treasurer_value = (\Auth::user()->isTreasurer()) ? 'Y' : 'N';
        \Session::set('is_admin', $admin_value);
        \Session::set('is_treasurer', $treasurer_value);
    }

 
You can then retrieve the session values on your view (or controller) like this:

VIEW:
@if (Session::get('is_admin') == 'Y')
    echo "Hello admin";
@endif

CONTROLLER:
if(\Session::get('is_admin') == 'Y'){
   echo "Hello admin";
}

 
We hope the above helps someone and we would like to know if anyone has had a different approach to this.
 
 

So, What do yout think?