Monday, 27 March 2017

Topic 15 - Custom Helper

Basically you need a helper , when you going standardize a certain function or code that going to be used at any view pages. This roughly bring the idea of using custom helper on which we can use the same code either to create buttons, forms or any elements that contain the same code.

There are few steps that we can follow in order to create custom helper :

First, you can create helper file in  app/helpers.php

There you can fill your own helper code and ready to be use.

<?php
// My helper function
function fullName($stringA,$stringB)
{
    return $stringA .' '. $stringB;
?>

In the example given, we are creating a helper function to combine firstname and lastname for our user using the fullName function. Then, we can assign our helper file into composer.json  autoload files.
{
    "autoload": {
        "files": [
            "app/helpers.php"
        ]
    }
}

And after that , run composer dumb-auto command on cmd

$ composer dump-auto

If you intent to include many helpers , then it will be better if you create helper files inside Helper folder just like this app/http/Helper/YourHelperName.php

Create a new helper file that will loop dynamically the required helpers. An example we named our file  HelperServiceProvider.php

public function register()
{
    foreach (glob(app_path().'/Helpers/*.php') as $filename){
        require_once($filename);
    }
}

Then register your helper folder inside service provider located at config/app.php


'providers' => [
    'App\Providers\HelperServiceProvider',
]
References :

https://laracasts.com/discuss/channels/general-discussion/creating-custom-helpers?page=1
http://laravel-recipes.com/recipes/50/creating-a-helpers-file

No comments:

Post a Comment