Add Your Custom Helpers in Laravel 5

2015-05-06 Laravel

Recently I reached to the point in my Laravel 5 application where I’ve started repeating some small parts of my code in many places. I knew that in the future it can easily get out of control when there will be a need to change something. Obviouslly solution like “search and replace” is something we even should not consider for a moment. Instead of repeating myself I created helper functions.

Helper functions are nothing else as your custom standalone PHP functions that you just include and call whereever it’s a must. Then, if you have to change anything, you do it just in one place – the function’s definition. Below I will show you, how I implemented custom helper functions in Laravel 5. If you find my way as inappropriate or completely wrong, please let me know. We all learn everyday and I know that in Laravel you can do one things in multiple ways.

Before we jump to the code, let’s think for a while about arranging our helper function in more organised way. What I did?

  1. Inside app directory I created another directory called Helpers.
  2. Inside Helpers I created individual files for functions that are designed to do some specific things (of course you’re free to change this – maybe it’s better for you just to create one single file called Functions.php):
    1. Text.php – for manipulating stings,
    2. Avatar.php – for displaying user’s avatar,
    3. General.php – for common and “general” things like returning some specific arrays, converting bytes to more “readable format” using kB, MB etc.
  3. Next I wrote a Service Provider that is responsible for including my functions.
  4. Last step is to edit app.php inside config directory and add specific code into “providers” and “aliases” arrays.

Let’s start. Inside

app

directory create another one called

Helpers

Next, inside create new file called

Text.php

Open this file and paste below code

<?php namespace Darwin\Helpers;

class Text {

    /**
     * Returns an excerpt from a given string (between 0 and passed limit variable).
     *
     * @param $string
     * @param int $limit
     * @param string $suffix
     * @return string
     */
    public static function shorten($string, $limit = 100, $suffix = '…')
    {
        if (strlen($string) < $limit) {
            return $string;
        }

        return substr($string, 0, $limit) . $suffix;
    }
}

Change the namespace to the one you use. As you see, we’ve defined one public static function called shorten. Keep in mind that this is just an example. We’ll ignore Avatar.php and General.php. You got the idea. Next, inside

app/Providers

create new file called

HelperServiceProvider.php

with the following content

<?php namespace Darwin\Providers;

use Illuminate\Support\ServiceProvider;

class HelperServiceProvider extends ServiceProvider {

   /**
    * Bootstrap the application services.
    *
    * @return void
    */
   public function boot()
   {
      //
   }

   /**
    * Register the application services.
    *
    * @return void
    */
   public function register()
   {
        foreach (glob(app_path().'/Helpers/*.php') as $filename){
            require_once($filename);
        }
   }
}

Again, adjust the namespace.

Next let’s tell Laravel about this Service Provider. Open

config/app.php

inside providers array add

'Darwin\Providers\HelperServiceProvider',

and inside aliases array add

'Text' => 'Darwin\Helpers\Text',

Guess what? We’re done.

Usage

How to use defined helper function?

Inside any view you can now use

<td><a href="{{ URL::route('article_show', [$article->id]) }}"
            title="{{ $article->title }}">{{ Text::shorten($article->title, 75) }}</a></td>

You just simply call a static function

Alias::static_function_name(param1, param2... param n)

How about controllers?

First tell Laravel where to look for the Text class. After the namespace definition add

use Darwin\Helpers\Text;

and now everywhere inside controller you can call shorten like

Flash::success('Article "' . Text::shorten($article->title, 50) . '" has been successfully created.');

I hope that my solution will be useful in your project.