How to create custom helper in Laravel 5?
In this tutorial, I will tell you how to create custom helper function in Laravel 5.
I usually create many helper class for MenuHelper to get menu html and also use for define payment gateway functionality.
You can also create helper function as per your need.
Here you will know how to create helper function in simple steps.
This helpfer function is mostly useful in view to format the data and return the results.
Step 1: Create Helper ClassIn this step we will create helper class so first create a directory where all helper class file will be saved.
I create a directory Libraries
within app directory and inside this directory we will create new General.php
PHP file.
- <?php
- namespace App\Libraries;
- class General {
- // function to get gravatar photo/image from gravatar.com using email id.
- public static function getGravatarURL($email, $s = 80, $d = 'mm', $r = 'g', $img = false, $atts = array())
- {
- $url = 'http://www.gravatar.com/avatar/';
- $url .= md5(strtolower(trim($email)));
- $url .= "?s=$s&d=$d&r=$r";
- if ($img)
- {
- $url = '<img src="' . $url . '"';
- foreach ($atts as $key => $val)
- $url .= ' ' . $key . '="' . $val . '"';
- $url .= ' />';
- }
- return $url;
- }
- }
In this step, we will add file path of helper class in composer.json file within autoload object.
- "autoload": {
- "files": [
- "app/Libraries/General.php"
- ]
- },
This is last step, here we will fire a command to dump the autoloader.
composer dump-autoload
Now you are ready to use this step to create a custom helper function in your application.
Example :
- Route::get('/', function(){
- $img='<img src="'.General::getGravatarURL('ajay.agrahari09@gmail.com').'">';
- echo $img;
- });