Lesson 6 – Custom Helper Function

You can considerably increase your development speed by creating custom helper functions. However, you need to take many different things into consideration while creating these functions. This is where this tutorial will come to your help.

Before we proceed with the tutorial, here a few things you need to remember.

  • Exceptions normally occur when we call the service provider twice. In order to prevent these exceptions, we have placed function definitions within the check function (function_exists).
  • Alternatively, you can use the composer.jason file to register the helper files. You can find the logic for this directly from the Laravel framework.
READ ALSO
Lesson 3 – Laravel Views

Now, we see some of the examples of how to create a custom helper class.

if (!function_exists('document')) {
    function document($text = '') {
    return $text;
    }

The above piece of code simply creates a helper.php file, for say, in app/Helpers/document.php. It is possible to put as many helper files as you want in a single file. Alternatively, you can split them as single files as well.

Now, we are also going to create a helper service provider. We will put the new services provider in the aptly named, app/providers folder.

<?php
namespace App\Providers;
class HelpersServiceProvider extends ServiceProvider
{
 public function register()
 {
 require_once __DIR__ . '/../Helpers/document.php';
 }
}

The service provider we have just created automatically registers your custom functions by loading the helper files.

READ ALSO
Lesson 10 – Laravel File System

It is not enough to create a service provider though. You also have to register it in config/app.php under providers as shown in the following example.

'providers' => [
    // [..] other providers
    App\Providers\HelpersServiceProvider::class,
   ]

Now that you have registered your service provider, it is possible to employ the document() function wherever you like in your code. In the following example, the function receives a string as an argument and returns it as output.

<?php
Route::get('document/{text}', function($text) {
 return document($text);
});

In the next lesson, we are going to discuss the directory structure in Laravel.