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 #3

Using Hashid with Laravel 5

Hashid can be used to to obfuscate id for the url of the web pages. Sometimes we want to prevent the id display for security reasons. Tonight I was working on it so thought to share my experience.

Hashid is a php open-source library which generates ids like  Youtube ids where the numeric id is being converted to alphabets. Example 123 converted to bnt. 

I have used this Laravel 5 wrapper for my project which can be installed via composer.

composer require vinkla/hashids

I have used it to hide the users id so that no one else can use it to edit others account. In user model I have added getRouteKey() method.

User.php

public function getRouteKey() {
    return Hashids::encode($this->getKey());
}

getRouteKey[Name] are implementation of the interface, which lets you create routes like before route(‘users.show’, $user->id) or easier route(‘users.show’, $user). Eloquent objects can be passed as route parameters and Laravel will to the job.

In the controller the id will be passed as obfuscated id therefore we need to decode it before passing the data to database or apply the business logic. Route binding is the easiest way of achieving this.

Routes.php

Route::bind('users', function($user)
{
   return Hashids::decode($user);
});

The userid is being decoded before it is being passed to the controller.

index.blade.php

Laravel does the job to fetch the userid from this.

<a href="{{ route('show_user', [$user]) }}">

Another method:

In the model

protected $appends = ['hashid'];
public function getHashidAttribute()
{
    return Hashids::encode($this->attributes['id']);
}

 

 

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')