How to create custom helper functions in Laravel

304,347

Solution 1

Create a helpers.php file in your app folder and load it up with composer:

"autoload": {
    "classmap": [
        ...
    ],
    "psr-4": {
        "App\\": "app/"
    },
    "files": [
        "app/helpers.php" // <---- ADD THIS
    ]
},

After adding that to your composer.json file, run the following command:

composer dump-autoload

If you don't like keeping your helpers.php file in your app directory (because it's not a PSR-4 namespaced class file), you can do what the laravel.com website does: store the helpers.php in the bootstrap directory. Remember to set it in your composer.json file:

"files": [
    "bootstrap/helpers.php"
]

Solution 2

Custom Classes in Laravel 5, the Easy Way

This answer is applicable to general custom classes within Laravel. For a more Blade-specific answer, see Custom Blade Directives in Laravel 5.

Step 1: Create your Helpers (or other custom class) file and give it a matching namespace. Write your class and method:

<?php // Code within app\Helpers\Helper.php

namespace App\Helpers;

class Helper
{
    public static function shout(string $string)
    {
        return strtoupper($string);
    }
}

Step 2: Create an alias:

<?php // Code within config/app.php

    'aliases' => [
     ...
        'Helper' => App\Helpers\Helper::class,
     ...

Step 3: Run composer dump-autoload in the project root

Step 4: Use it in your Blade template:

<!-- Code within resources/views/template.blade.php -->

{!! Helper::shout('this is how to use autoloading correctly!!') !!}

Extra Credit: Use this class anywhere in your Laravel app:

<?php // Code within app/Http/Controllers/SomeController.php

namespace App\Http\Controllers;

use Helper;

class SomeController extends Controller
{

    public function __construct()
    {
        Helper::shout('now i\'m using my helper class in a controller!!');
    }
    ...

Source: http://www.php-fig.org/psr/psr-4/

Why it works: https://github.com/laravel/framework/blob/master/src/Illuminate/Support/ClassLoader.php

Where autoloading originates from: http://php.net/manual/en/language.oop5.autoload.php

Solution 3

my initial thought was the composer autoload as well, but it didn't feel very Laravel 5ish to me. L5 makes heavy use of Service Providers, they are what bootstraps your application.

To start off I created a folder in my app directory called Helpers. Then within the Helpers folder I added files for functions I wanted to add. Having a folder with multiple files allows us to avoid one big file that gets too long and unmanageable.

Next I created a HelperServiceProvider.php by running the artisan command:

artisan make:provider HelperServiceProvider

Within the register method I added this snippet

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

lastly register the service provider in your config/app.php in the providers array

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

now any file in your Helpers directory is loaded, and ready for use.

UPDATE 2016-02-22

There are a lot of good options here, but if my answer works for you, I went ahead and made a package for including helpers this way. You can either use the package for inspiration or feel free to download it with Composer as well. It has some built in helpers that I use often (but which are all inactive by default) and allows you to make your own custom helpers with a simple Artisan generator. It also addresses the suggestion one responder had of using a mapper and allows you to explicitly define the custom helpers to load, or by default, automatically load all PHP files in your helper directory. Feedback and PRs are much appreciated!

composer require browner12/helpers

Github: browner12/helpers

Solution 4

This is what is suggested by JeffreyWay in this Laracasts Discussion.

  1. Within your app/Http directory, create a helpers.php file and add your functions.
  2. Within composer.json, in the autoload block, add "files": ["app/Http/helpers.php"].
  3. Run composer dump-autoload.

Solution 5

Having sifted through a variety of answers on SO and Google, I still couldn't find an optimal approach. Most answers suggest we leave the application and rely on 3rd party tool Composer to do the job, but I'm not convinced coupling to a tool just to include a file is wise.

Andrew Brown's answer came the closest to how I think it should be approached, but (at least in 5.1), the service provider step is unnecessary. Heisian's answer highlights the use of PSR-4 which brings us one step closer. Here's my final implementation for helpers in views:

First, create a helper file anywhere in your apps directory, with a namespace:

namespace App\Helpers;

class BobFinder
{
    static function bob()
    {
        return '<strong>Bob?! Is that you?!</strong>';
    }
}

Next, alias your class in config\app.php, in the aliases array:

'aliases' => [
    // Other aliases
    'BobFinder' => App\Helpers\BobFinder::class
]

And that should be all you need to do. PSR-4 and the alias should expose the helper to your views, so in your view, if you type:

{!! BobFinder::bob() !!}

It should output:

<strong>Bob?! Is that you?!</strong>
Share:
304,347
Calebe Oliveira
Author by

Calebe Oliveira

Updated on December 27, 2021

Comments

  • Calebe Oliveira
    Calebe Oliveira over 2 years

    I would like to create helper functions to avoid repeating code between views in Laravel. For example:

    view.blade.php

    <p>Foo Formated text: {{ fooFormatText($text) }}</p>
    

    They're basically text formatting functions. How should I define globally available helper functions like fooFormatText()?

  • Andrew Brown
    Andrew Brown about 9 years
    for people who only have a few functions they need to add, the composer autoload is perfectly fine, but for those of us that may have a lot of helper functions, multiple file organization is a must. this solution is essentially what I did in L4 except I registered the files in my start.php file (which wasn't great, but served its purpose for the time). do you have another suggestion for loading multiple files?
  • Joseph Silber
    Joseph Silber about 9 years
    If you have multiple files, add them all to your composer.json file. Adding even 5-10 lines there makes way more sense than what you have here.
  • Rizerzero
    Rizerzero about 9 years
    i like it too . small files , just used when needed , i have no idea why i would have them all in one file or have to change composer each time i add a function to an app .
  • impeto
    impeto about 9 years
    I think this technique has a lot of merit. It's elegant and efficient because you don't have to remember to mess with the composer.json file every time you create a helper file.
  • Pablo Ezequiel Leone
    Pablo Ezequiel Leone about 9 years
    Really good solution. The only thing I disagree is the way you add the files, I think should be a mapper instead, where we add the name of the file we want to load. Think on errors! if there is just one helper in one of the files that is failing, then you should remove all of them, or have the site broken till you solve it.
  • Allfarid Morales García
    Allfarid Morales García almost 9 years
    Tip for noobs: use this command after changing composer.json. composer dump-autoload
  • Matt McDonald
    Matt McDonald almost 9 years
    @AllfaridMoralesGarcía Or perhaps just 'A useful tip, as the answer doesn't make it clear you need to do this afterwards'.
  • Cengkaruk
    Cengkaruk almost 9 years
    Do you use App\Providers namespace? How i call that helper from controller and view. Sorry, noob question.
  • Andrew Brown
    Andrew Brown almost 9 years
    using this method all of the helpers will be autoloaded, so you can simply call your function anywhere in your application.
  • enchance
    enchance almost 9 years
    I somewhat agree with this solution but not so wholly. But I do agree that loading non-class files need a framework-esque solution and this does it just fine. Other than loading helpers, not all libraries are classes (especially the old ones) so in case you have to load a non-class file then this is it.
  • Christopher
    Christopher almost 9 years
    @PabloEzequielLeoneSignetti How to add a mapper? Can you provide an example?
  • andrewtweber
    andrewtweber over 8 years
    I approve of helper functions to make writing views easier but I hate how much this answer is referenced in other answers. Don't get me wrong, it's a good answer and correct, I just fear that people will abuse it and start writing tons of poorly written, poorly organized functional PHP again.
  • The Unknown Dev
    The Unknown Dev over 8 years
    This seems to work for me, I just had to use $this->app->basePath . '/app/Http/Helpers/*.php' in the glob() for that to work. app_path() wasn't defined in my case.
  • Pelmered
    Pelmered over 8 years
    Are there any other reasons than performance to create a mapper instead of loading all the files in the directory with glob() as Andrew Brown wrote? If you want to be able to specify the files that you want to include, why not specify the files in the composer.json to autoload them as Joseph Silber wrote? Why do you prefer this solution? I'm not saying this is a bad solution, I'm just curious.
  • heisian
    heisian over 8 years
    I think manually including php files goes directly against what Laravel was designed to do. Please see my answer below for including custom classes as intended.
  • heisian
    heisian over 8 years
    I'm not sure why it's necessary to autoload the file individually - even in Laravel 4 this wasn't necessary.
  • Thomas Cheng
    Thomas Cheng over 8 years
    Actually sorry, meant no offense, but I tend to agree with @JosephSilber. The reason why is because usually you'd want these classes to be as loosely coupled with the framework as possible. Let's say one day you have to change your framework, you would want the helpers to work by themselves. With Composer, you don't need to modify a line. You don't want to write it "Too Laravel", though Laravel is a great framework of course.
  • MetalFrog
    MetalFrog over 8 years
    I think is a strange implementation. If you're winding up with so many helper functions that you need to split them into multiple files, I think you're creating way too many global functions. Creating a file per method is asinine, as is requiring every file pre-emptively.
  • Dan Hunsaker
    Dan Hunsaker over 8 years
    To be clear, this answer doesn't actually deal with helpers, which are global-namespaced functions. Instead, it encourages converting helpers to class methods. This is generally the best approach, but doesn't actually answer the question asked here, which is why other answers are so complex by comparison.
  • Dan Hunsaker
    Dan Hunsaker over 8 years
    It's easier, with a mapped approach, to selectively enable/disable helpers if, for example, one of the helper files contains a breaking error. That said, mapping files in a service provider is not very different from doing so in composer.json except for two points - first, it keeps the map inside the application itself, rather than a metadata file; second, it doesn't require you to re-run composer dump-autoload every time you change the list of files to load.
  • dKen
    dKen over 8 years
    I don't understand this approach. Composer is supposed to be a tool to include libraries: Laravel would work perfectly well without it, and Composer without Laravel. This suggestion tells us to create a file within our app, leave our app, go to Composer, tell composer to go back into our app and include a file. Laravel clearly handles the inclusion of files, right? Why would we forgo Laravel's native implementation and use this external tool to include a file for us, thus coupling our application to Composer more? Is it laziness, or am I missing something?
  • Phillip Harrington
    Phillip Harrington over 8 years
    Laravel uses composer's autoloader to know where to include all the libraries and files it relies on. This referenced in bootstrap/autoload.php. Read the comment in that file. The approach is to add the reference to the file into the composer.json, then "dump autoload," which regenerates composer's autoloader so that Laravel can find it. Using Composer's "files" collection is a good way to add libraries or one-off function files that aren't neatly wrapped up in composer packages. It's nice to have a place for all the "by the way I have to include this one weird file" situations.
  • dKen
    dKen over 8 years
    Thanks @PhillipHarrington, makes sense to some degree. I still think that if it's possible to resolve this using a class file and either a line in Composer, or a line in Laravel, one is more maintainable, less coupled and easier to understand than the other, especially for those who, for some reason, don't like composer. Maybe it's a personal preference thing, but for some reason it makes me feel dirty :(
  • heisian
    heisian over 8 years
    thanks for posting this. as @Dan-Hunsaker pointed out in my solution we still have not ended up with a globally-namespaced function, i.e. being able to write simply {!! bob() !!}. going to do some more searching and see if that is possible
  • heisian
    heisian over 8 years
    I've thought about it more and attempting to make bob() truly global would not be a wise thing to do. Namespaces are there for a reason and we shouldn't be calling bob() alongside base PHP functions. I'll be adding your aliasing bit to my code - thanks!
  • sepehr
    sepehr over 8 years
    The helpers might not be HTTP-only. app/helpers.php or app/Helpers/ seems to be a better place.
  • Jimmy Obonyo Abor
    Jimmy Obonyo Abor over 8 years
    I find this to be a the best of all
  • Ricardo Vigatti
    Ricardo Vigatti over 8 years
    Ok so, based on all those comments, seems that each variant for this solution is good. If you write custom helper functions that makes use of Laravel Framework itself, it's better to do like @PabloEzequielLeoneSignetti says. But, if you are writing helper functions that can be used anywhere, maybe is better to do like Joseph Silber says, including it on the composer.json file.
  • bernie
    bernie over 8 years
    Why is there extends Helper? It doesn't seem necessary for me.
  • MaXi32
    MaXi32 over 8 years
    Function helper means it is available in Blade as well.How do you make this function available in blade? You cannot call Helper::prettyJason(parameters) in blade.
  • Ash
    Ash over 8 years
    "do you have another suggestion for loading multiple files?" Yes, register your helper functions inside a file relating to your package like Illuminate/Foundation/helpers.php and correctly use Packages. Also instead of glob you should load the FileSystem from the container.
  • user3201500
    user3201500 over 8 years
    What if we are on a shared server and dont have option to use composer dump-autoload ?
  • itsazzad
    itsazzad over 8 years
    @user3201500 that is another question and you may need to do manually if you want to follow the above answer. Or you can choose from other answers. And to manually reflect the composer dump-autoload you may follow this: developed.be/2014/08/29/composer-dump-autoload-laravel
  • dKen
    dKen over 8 years
    @bernie @user3201500 Sorry team, I had my own base helper class that all my helpers inherit from; the extends Helper is indeed not necessary. Thanks for the heads up.
  • Andrew Brown
    Andrew Brown about 8 years
    i am not a huge fan of Facades and like to avoid them when possible, but if you are okay with them this is a very good solution as well.
  • dKen
    dKen about 8 years
    @AndrewBrown Unfortunately almost every example in the Laravel docs uses facades, without any warnings or suggestions for when and when not to use them. It makes it very difficult for newcomers to Laravel to know they have an option to not use them, and what the impact of that is.
  • Rick Jolly
    Rick Jolly about 8 years
    @AndrewBrown there are no Facades here - just php static methods. Essentially namespaced functions. I agree that Facades are a ridiculous nonstandard obfuscation though.
  • code-8
    code-8 about 8 years
    "files": [ "app/helpers.php", "app/second.php" ] - if I want to autoload more than one file, can I just keep appending like this ?
  • Gerard Reches
    Gerard Reches about 8 years
    @AndrewBrown When you add the provider to the providers array it should be App\Providers\HelperServiceProvider::class not App\Providers\HelperServiceProvider, right? I'm trying this method but for some reason Laravel not recognize my functions :s
  • Andrew Brown
    Andrew Brown about 8 years
    all that ::class does is return a string of the class name, so you can do it that way, or just write the string in yourself.
  • heisian
    heisian about 8 years
    You don't need to add files to composer.json for them to be autoloaded. Laravel's already got a built-in class loader: github.com/laravel/framework/blob/master/src/Illuminate/Supp‌​ort/… Just create a class file in a directory with a matching namespace and Laravel will automatically include the file/class in your project. You don't even need to run composer dump-autoload. Just use a use statement for the class where ever you need it.
  • heisian
    heisian about 8 years
    @PhillipHarrington php-fig.org/psr/psr-4 No need to mess with composer.json. A file with matching directory structure and namespace is enough for Laravel 5 to autoload your custom class.
  • heisian
    heisian about 8 years
    @AndrewBrown this is not a facade. This is PSR-4 autoloading. php-fig.org/psr/psr-4
  • heisian
    heisian about 8 years
    @MaXi32 you could add the class under the aliases array in app/config.php: 'Helper' => App\Helpers\Helper::class, Then you would be able to call Helper::prettyJson(); in blade just fine.
  • heisian
    heisian about 8 years
    No need for include or require, Laravel already has built-in PSR-4 autoloading: php-fig.org/psr/psr-4
  • heisian
    heisian about 8 years
    Guys, this answer is essentially re-writing an already-made ClassLoader found in Laravel: github.com/laravel/framework/blob/master/src/Illuminate/Supp‌​ort/… There is no reason to re-write code that's already built into the framework.
  • heisian
    heisian about 8 years
    @dKen Take a look at the Laravel source: github.com/laravel/framework/blob/master/src/Illuminate/Supp‌​ort/… Class-loading is already built into Laravel, that's how my and your answer works.
  • Pablo Ezequiel Leone
    Pablo Ezequiel Leone about 8 years
    using PSR-4 and composer won't allow you to switch on/off helpers.
  • heisian
    heisian about 8 years
    @DanHunsaker edited to directly answer the question, and it's still the same simple approach. You can also just write your own custom blade directives: stackoverflow.com/questions/28290332/…
  • Dan Hunsaker
    Dan Hunsaker about 8 years
    @heisian while I agree this is the correct answer, it still doesn't actually give you access to helpers. That's all I was intending to point out to the previous commenter. I personally favor discontinuing use of helpers (which are, to be clear, global functions, rather than class methods) in favor of this approach, for all the reasons stated elsewhere on this page. (Though since the OP explicitly wanted a helper for their views, the Blade directive approach is, perhaps, even better for answering the specific question asked here.)
  • heisian
    heisian about 8 years
    @DanHunsaker Well, here's the framework source for where helpers are defined: github.com/laravel/framework/blob/master/src/Illuminate/… No namespacing, so this file is loaded somewhere in Laravel without the help of the ClassLoader.. so to extend these types of functions the way to do it would be as others have said is to do a manual require or include. I don't know though, some people's obsession is with being able to call myGlobalFunction() whereas my obsession is VerySpecificClass::method().. I just think it encourages proper organization.
  • Dan Hunsaker
    Dan Hunsaker about 8 years
    Yeah, I dug through the framework once and found where they pulled the helpers in. And again, I completely agree that methods of namespaced static classes are a much cleaner fit than what's being requested - or recommended - most of the time. The fact is, helpers aren't really The Laravel Way in the first place, but rather a holdover from CodeIgniter 2.x that still hasn't been phased out. So my pedantry about this approach not answering the OP exactly as asked is more an attempt to highlight the fact that you don't get helpers, but rather something better.
  • heisian
    heisian almost 8 years
    so perhaps an all-encompassing answer would say, hey, this is how you can create global helpers (w/ code examples), but there is actually a more "friendly" way to do things, and this is what I recommend instead.
  • P_95
    P_95 almost 8 years
    This works well. But should it be /config/app.php not /app/config.php (Step 2)
  • Kenyon
    Kenyon over 7 years
    Except the whole point of this helpers file is to be outside of a class scope. Also, Laravel is dependent on Composer. Natively, Laravel won't work without Composer. They are independent, but they're still coupled. I think adding a require statement in Laravel is a worse solution than in a composer.json because you know have things being loaded in multiple places, thus, less maintainable.
  • OverCoder
    OverCoder over 7 years
    Helpers.php is more convenient than helpers.php
  • goredwards
    goredwards over 7 years
    @heisian your alias definition should be 'Helper' => App\Helpers\Helper::class, (ie quotes around the key but no quotes around the value) - or it will throw a Class Helper does not exist error
  • Mubashar Abbas
    Mubashar Abbas about 7 years
    in laravel 5.3 they make a point of app/ directory being a completely psr-4 autoloaded dir. Thats why they removed the routes.php to a separate folder outside of app. What should we do now?
  • David Barker
    David Barker about 7 years
    @MubasharAbbas You answered your own question. Move your helpers into a different location outside of app/ and point composer there instead.
  • stef
    stef about 7 years
    This gives me an error:: Argument 1 passed to App\Helpers\Helper::shout() must be an instance of App\Helpers\string, string given. Something to do with scalar type hinting?
  • omarjebari
    omarjebari almost 7 years
    This is the best answer but you don't even need to create an alias for this class, certainly not in 5.4 anyway. Create a class somewhere convenient for you, eg App/Libraries/Helper.php class Helper() {
  • M_Idrees
    M_Idrees almost 7 years
    I was getting error message as not valid json. Then I removed the comments "// <---- ADD THIS" from "files" tag, then the command "composer dump-autoload" works fine.
  • Akshay Khale
    Akshay Khale almost 7 years
    composer dump-autoload and composer dumpautoload also works infact composer du will also work...
  • VinGarcia
    VinGarcia over 6 years
    @PabloEzequielLeone and how would I use it inside a controller or a blade file? This looks as the best option if you are concerned with not loading all the helpers for all the controllers everytime, but is not good for beginners in Laravel (like myself).
  • Bartłomiej Sobieszek
    Bartłomiej Sobieszek over 6 years
    This is not a correct answer, this will work, but this is most incorrect approach a programmer could make to solve this problem.
  • Felipe Valdes
    Felipe Valdes over 6 years
    Thank you, would you mind expanding a bit on your explaination?
  • FabioCosta
    FabioCosta over 6 years
    Wouldn't that 'Use helper' throw an The use statement with non-compound name 'Helper' has no effect in... ?
  • heisian
    heisian over 6 years
    This answer was written for Laravel 5.1, feel free to propose any edits for the latest version.. I haven't used it yet.
  • Arcesilas
    Arcesilas about 6 years
    If the class is namespaced, adding the file in composer.json is useless, since psr-4 autoload will do the job.
  • JamesG
    JamesG almost 6 years
    I agree with @DavidBarker - this is not the correct answer. It is wrong to put this file in the app directory. This point is clearly evidenced by the fact that Taylor moved the routes file OUT of the app directory.
  • Evol Rof
    Evol Rof almost 6 years
    finally find a way that can be used in blade
  • despotbg
    despotbg almost 6 years
    Looks like this method is deprecated in new Laravel version... I try with Laravel 5.6 but I keep getting error "Class 'Helper' not found..."
  • Aleksandrs
    Aleksandrs almost 6 years
    This should be marked the best answer, because question was "to avoid repeating code between some views". Keyword is VIEWS. :)
  • Oluwatobi Samuel Omisakin
    Oluwatobi Samuel Omisakin over 5 years
    Its surprising how a simple question like this could have generated several opinions that deviate from the question. The simple question "how to create...helper functions...in L5 style" How to do it the way its done on L5. Simple! Apart from not putting the helper file in app directory this is the simplest way to do it. There's no need for Facade/Static functions etc...
  • codingbruh
    codingbruh over 5 years
    Thanks your answer helped me. but just one question when I stored my helper file in bootstrap directory, composer dump-autoload gave me warnings and errors saying it can't find the path. I check twice, the path was correct.
  • Joseph Silber
    Joseph Silber over 5 years
    @djangodude - Can you post two screenshots? One of your directory structure, the other of your composer.json autoload section.
  • Jed Lynch
    Jed Lynch over 5 years
    This solution makes the most sense. Any application should work with in laravel framework, especially if you are a part of a team of developers. Composer.json should only change if you adding vendor libraries (and as few as possible should be added). Stitching a script to the composer.json file invites future developers to this pseudo app dumping ground that is not bound to any context with in the framework. I don't why that is the winning answer. That solution wouldn't make it through code review where I work.
  • Yevgeniy Afanasyev
    Yevgeniy Afanasyev about 5 years
    This answer works, but gives problems to NetBeans users
  • Jed Lynch
    Jed Lynch about 5 years
    I cannot stress how much that this is the wrong way to setup a helper. The correct way is to create a class and alias it (see answer below). However, if you have a helper that so complex that it needs to be it's own app create a laravel package seen here... laravel.com/docs/5.8/packages
  • Amitesh Bharti
    Amitesh Bharti almost 4 years
    Does it required to run composer dump-autoload everytime when helper.php changes?
  • Mark
    Mark over 3 years
    @heisian how do you pass a variable into the custom directive?
  • Kolawole Emmanuel Izzy
    Kolawole Emmanuel Izzy over 3 years
    You mentioned that you added different helper libraries in your app/Libraries folder but only added one file in your composer.json file. did you include the helper files in the commonFunction.php file?
  • Axel Paris
    Axel Paris about 3 years
    For Laravel 8 (I tested on this version), just before the composer dump-autoload, you need to run : php artisan config:cache to clear the cache of the file config/app.php. Then it will work
  • Tharindu Thisarasinghe
    Tharindu Thisarasinghe about 3 years
    This worked like a charm! I had almost a day wasted for this and then I found this answer. Thanks a lot!
  • Kamlesh
    Kamlesh about 3 years
    @abhishekkumar - any suggestion for Lumen 8.0. Thanks in advance.
  • Kamlesh
    Kamlesh about 3 years
    I have tried same solution for the Lumen 8 but getting error "Fatal error: Cannot declare class MasterFunctionsHelper, because the name is already in use in /Applications/MAMP/htdocs/laravelprojects/project_api/app/He‌​lpers/MasterFunction‌​sHelper.php on line 3"
  • abhishek kumar
    abhishek kumar about 3 years
    @Kamlesh namespace problem, this link will help you stackoverflow.com/questions/40406418/…
  • Eric Aya
    Eric Aya over 2 years
    This is very similar to the solution in the accepted answer. When answering older questions that already have answers, please make sure you provide either a novel solution or a significantly better explanation than existing answers.
  • giò
    giò about 2 years
    link not working