Laravel Tips #4

Last Login event registration

Today I worked on my application to record last login date and time for the users. After reading this documentation this is how I implemented in my project.

protected $listen = [
    'Illuminate\Auth\Events\Login' => [
        'App\Listeners\LogLastLogin',
    ],
];

Then ran the artisan command

php artisan event:generate

This artisan command generate events and listeners.
Then update the handle method under Listeners\LogLastLogin.php

public function handle(Login $event)
{
    $event->user->last_login = date('Y-m-d H:i:s');
    $event->user->save();
}

Tested and its working fine. Happy days!!!

Laravel Tips #2

Closed-based routes vs Controller
Closure function – allows to skip the controllers and perform business logic and generate views. Helps to prototype applications quickly or ideal for testing purpose.
As the application grows closed-based routes will become very complex and confusing.
Route::get('cats/{cat}/edit', function(Furbook\Cat $cat) {
    return view('cats.edit')->with('cat', $cat);
});
Controller – loads a dedicated class and easy to maintain.
Routes using controller
Route::resource('users', 'UsersController', [
    'names' => [
        'create' => 'create_user',
        'index'  => 'users_preview',
        'store' => 'save_users',
        'destroy' => 'user_delete',
        'edit' => 'edit_user',
    ]
]);
Controller
public function index()
{

  $users_array = $this->company->companyUsers(Auth::user()->company->first()->id);
   return view("Users::index", compact('users_array'));
}
It better to use the MVC principle and separate the business logic and let route just do the routing job only.

Laravel Tips #1

Helper function – array_add() (laravel 5.2): link

The method appends the key/value pair  to the existing array.  This can be useful when adding additional fields when creating new record with request all() method. If the form and database field names are same than just pass the request->all() method. If you still see that the input is not creating new record than you must define all your fillable fields under the model.

For example:

$new_department = Department::create(array_add($request->all(),'company_id',Auth::user()->company->first()->id));

or

$data = $request->all();
$data['company_id'] = Auth::user()->company->first()->id;
Department::create($data);

Use pluck vs list (laravel 5.2) : link 

The pluck method returns an array. Both method to do the same thing.

For example:

 $this->departments->whereCompanyId(Auth::user()->company->first()->id)->pluck('name', 'id')