Kenneth_H's avatar

Creating custom helpers

Hi As part of moving a larger application from CodeIgniter to Laravel 5, as it gives me a lot of flexibility where I had to do a few "hacks" to get working in CI, I have now come to a point where I have to migrate some helper functions. I have been searching some time on the internet to find the way of doing this, but I cannot really find any solution for accessing the application object from within a helper function. Fx. I have a function for getting a translated string from a database table. In CI I had a method called get_instance() that created a reference variable for the CI instance, but how to I do this in Laravel and is there a better way of doing this when I have to access the instance of Laravel, but want to be able to reference just the function name in my views?

0 likes
6 replies
callam's avatar
callam
Best Answer
Level 2

Depending on how many helper functions you intend to move over, I suggest two options:

  • Create app/Http/helpers.php and move all of your functions into there
  • Add the helpers.php file to your composer.json autoload files
{
    "autoload": {
        "files": [
            "app/helpers.php"
        ]
    }
}

However, if you have a lot of helper functions or they contain a large amount of logic, I'd suggest creating helper files foreach individual functionality:

  • Create app/Http/Helpers/TranslatedStringHelper.php and add the corresponding function(s)
  • Create a new HelperServiceProvider.php and add loop to dynamically require helpers
public function register()
{
    foreach (glob(app_path().'/Helpers/*.php') as $filename){
        require_once($filename);
    }
}
  • Register the service provider in your config/app.php
'providers' => [
    'App\Providers\HelperServiceProvider',
]

In both cases, you should now be able to use the functions define within the helper file(s) you have created. Using just one file to contain all of your helper functions can become hard to maintain so I'd suggest the latter as it is a more object oriented approach.

3 likes
sukonovs's avatar

You can add classmap or file in composer.json. You can make "Helpers" class with static functions. Many ways to go about it.

Kenneth_H's avatar

Ok. But how would I access the translations table in my database from within these helpers?

When I have the instance of laravel, it is easy as I have eloquent, but I do not have that directly in my helpers?

callam's avatar

@Kenneth_H To access your translations table, you can use DB::table('translations')

$translations = DB::table('translations')->get();
Kenneth_H's avatar

Ok. But what about configuration entries? I need to get the locale property from the config/app.php? Can I use the Configuration classes get() method for that?

Please or to participate in this conversation.