I would like to create some helpers (functions) to avoid repeating code between some views, in L5 style:

view.blade.php

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

They are basically text formatting functions. Where and how can I put a file with these functions?

20 Answers 11

up vote 346 down vote accepted

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
44 upvote
  flag
Tip for noobs: use this command after changing composer.json. composer dump-autoload – Allfarid Morales García
8 upvote
  flag
@AllfaridMoralesGarcía Or perhaps just 'A useful tip, as the answer doesn't make it clear you need to do this afterwards'. – Matt McDonald
7 upvote
  flag
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. – andrewtweber
upvote
  flag
I'm not sure why it's necessary to autoload the file individually - even in Laravel 4 this wasn't necessary. – heisian
19 upvote
  flag
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? – dKen
upvote
  flag
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. – Phillip Harrington
2 upvote
  flag
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 :( – dKen
upvote
  flag
@dKen - It's important to not feel dirty when coding. I totally get that :-) – Phillip Harrington
upvote
  flag
"files": [ "app/helpers.php", "app/second.php" ] - if I want to autoload more than one file, can I just keep appending like this ? – ihue
upvote
  flag
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
upvote
  flag
@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
upvote
  flag
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. – Kenyon
upvote
  flag
Helpers.php is more convenient than helpers.php – OverCoder
1 upvote
  flag
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? – Mubashar Abbas
1 upvote
  flag
@MubasharAbbas You answered your own question. Move your helpers into a different location outside of app/ and point composer there instead. – David Barker
upvote
  flag
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. – M_Idrees
upvote
  flag
This is not a correct answer, this will work, but this is most incorrect approach a programmer could make to solve this problem. – Bartłomiej Sobieszek

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

27 upvote
  flag
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? – Andrew Brown
7 upvote
  flag
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. – Joseph Silber
upvote
  flag
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 . – Rizerzero
20 upvote
  flag
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. – impeto
8 upvote
  flag
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. – Pablo Ezequiel Leone
3 upvote
  flag
Do you use App\Providers namespace? How i call that helper from controller and view. Sorry, noob question. – Cengkaruk
upvote
  flag
using this method all of the helpers will be autoloaded, so you can simply call your function anywhere in your application. – Andrew Brown
upvote
  flag
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. – enchance
1 upvote
  flag
@PabloEzequielLeoneSignetti How to add a mapper? Can you provide an example? – Christopher
upvote
  flag
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. – Kimberly W
1 upvote
  flag
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
upvote
  flag
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. – Thomas Cheng
2 upvote
  flag
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. – MetalFrog
upvote
  flag
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. – Ricardo Vigatti
upvote
  flag
"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. – ash
upvote
  flag
@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 – Gerard Reches
upvote
  flag
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. – Andrew Brown
upvote
  flag
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

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.
10 upvote
  flag
The helpers might not be HTTP-only. app/helpers.php or app/Helpers/ seems to be a better place. – sepehr
1 upvote
  flag
What if we are on a shared server and dont have option to use composer dump-autoload ? – user3201500
upvote
  flag
@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 – itsazzad

This is my HelpersProvider.php file:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class HelperServiceProvider extends ServiceProvider
{
    protected $helpers = [
        // Add your helpers in here
    ];

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

    /**
     * Register the application services.
     */
    public function register()
    {
        foreach ($this->helpers as $helper) {
            $helper_path = app_path().'/Helpers/'.$helper.'.php';

            if (\File::isFile($helper_path)) {
                require_once $helper_path;
            }
        }
    }
}

You should create a folder called Helpers under the app folder, then create file called whatever.php inside and add the string whatever inside the $helpers array.

Done!

Edit

I'm no longer using this option, I'm currently using composer to load static files like helpers.

You can add the helpers directly at:

...
"autoload": {
    "files": [
        "app/helpers/my_helper.php",
        ...
    ]
},
...
upvote
  flag
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. – Pelmered
3 upvote
  flag
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. – Dan Hunsaker
upvote
  flag
No need for include or require, Laravel already has built-in PSR-4 autoloading: php-fig.org/psr/psr-4 – heisian
1 upvote
  flag
using PSR-4 and composer won't allow you to switch on/off helpers. – Pablo Ezequiel Leone
upvote
  flag
@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). – VinGarcia

Here's a bash shell script I created to make Laravel 5 facades very quickly.

Run this in your Laravel 5 installation directory.

Call it like this:

make_facade.sh -f <facade_name> -n '<namespace_prefix>'

Example:

make_facade.sh -f helper -n 'App\MyApp'

If you run that example, it will create the directories Facades and Providers under 'your_laravel_installation_dir/app/MyApp'.

It will create the following 3 files and will also output them to the screen:

./app/MyApp/Facades/Helper.php
./app/MyApp/Facades/HelperFacade.php
./app/MyApp/Providers/HelperServiceProvider.php

After it is done, it will display a message similar to the following:

===========================
    Finished
===========================

Add these lines to config/app.php:
----------------------------------
Providers: App\MyApp\Providers\HelperServiceProvider,
Alias: 'Helper' => 'App\MyApp\Facades\HelperFacade',

So update the Providers and Alias list in 'config/app.php'

Run composer -o dumpautoload

The "./app/MyApp/Facades/Helper.php" will originally look like this:

<?php

namespace App\MyApp\Facades;


class Helper
{
    //
}

Now just add your methods in "./app/MyApp/Facades/Helper.php".

Here is what "./app/MyApp/Facades/Helper.php" looks like after I added a Helper function.

<?php

namespace App\MyApp\Facades;

use Request;

class Helper
{
    public function isActive($pattern = null, $include_class = false)
    {
        return ((Request::is($pattern)) ? (($include_class) ? 'class="active"' : 'active' ) : '');
    }
}

This is how it would be called:
===============================

{!!  Helper::isActive('help', true) !!}

This function expects a pattern and can accept an optional second boolean argument.

If the current URL matches the pattern passed to it, it will output 'active' (or 'class="active"' if you add 'true' as a second argument to the function call).

I use it to highlight the menu that is active.

Below is the source code for my script. I hope you find it useful and please let me know if you have any problems with it.

#!/bin/bash

display_syntax(){
    echo ""
    echo "  The Syntax is like this:"
    echo "  ========================"
    echo "      "$(basename $0)" -f <facade_name> -n '<namespace_prefix>'"
    echo ""
    echo "  Example:"
    echo "  ========"
    echo "      "$(basename $0) -f test -n "'App\MyAppDirectory'"
    echo ""
}


if [ $# -ne 4 ]
then
    echo ""
    display_syntax
    exit
else
# Use > 0 to consume one or more arguments per pass in the loop (e.g.
# some arguments don't have a corresponding value to go with it such
# as in the --default example).
    while [[ $# > 0 ]]
    do
        key="$1"
            case $key in
            -n|--namespace_prefix)
            namespace_prefix_in="$2"
            echo ""
            shift # past argument
            ;;
            -f|--facade)
            facade_name_in="$2"
            shift # past argument
            ;;
            *)
                    # unknown option
            ;;
        esac
        shift # past argument or value
    done
fi
echo Facade Name = ${facade_name_in}
echo Namespace Prefix = $(echo ${namespace_prefix_in} | sed -e 's#\\#\\\\#')
echo ""
}


function display_start_banner(){

    echo '**********************************************************'
    echo '*          STARTING LARAVEL MAKE FACADE SCRIPT'
    echo '**********************************************************'
}

#  Init the Vars that I can in the beginning
function init_and_export_vars(){
    echo
    echo "INIT and EXPORT VARS"
    echo "===================="
    #   Substitution Tokens:
    #
    #   Tokens:
    #   {namespace_prefix}
    #   {namespace_prefix_lowerfirstchar}
    #   {facade_name_upcase}
    #   {facade_name_lowercase}
    #


    namespace_prefix=$(echo ${namespace_prefix_in} | sed -e 's#\\#\\\\#')
    namespace_prefix_lowerfirstchar=$(echo ${namespace_prefix_in} | sed -e 's#\\#/#g' -e 's/^\(.\)/\l\1/g')
    facade_name_upcase=$(echo ${facade_name_in} | sed -e 's/\b\(.\)/\u\1/')
    facade_name_lowercase=$(echo ${facade_name_in} | awk '{print tolower($0)}')


#   Filename: {facade_name_upcase}.php  -  SOURCE TEMPLATE
source_template='<?php

namespace {namespace_prefix}\Facades;

class {facade_name_upcase}
{
    //
}
'


#  Filename: {facade_name_upcase}ServiceProvider.php    -   SERVICE PROVIDER TEMPLATE
serviceProvider_template='<?php

namespace {namespace_prefix}\Providers;

use Illuminate\Support\ServiceProvider;
use App;


class {facade_name_upcase}ServiceProvider extends ServiceProvider {

    public function boot()
    {
        //
    }

    public function register()
    {
        App::bind("{facade_name_lowercase}", function()
        {
            return new \{namespace_prefix}\Facades\{facade_name_upcase};
        });
    }

}
'

#  {facade_name_upcase}Facade.php   -   FACADE TEMPLATE
facade_template='<?php

namespace {namespace_prefix}\Facades;

use Illuminate\Support\Facades\Facade;

class {facade_name_upcase}Facade extends Facade {

    protected static function getFacadeAccessor() { return "{facade_name_lowercase}"; }
}
'
}


function checkDirectoryExists(){
    if [ ! -d ${namespace_prefix_lowerfirstchar} ]
    then
        echo ""
        echo "Can't find the namespace: "${namespace_prefix_in}
        echo ""
        echo "*** NOTE:"
        echo "           Make sure the namspace directory exists and"
        echo "           you use quotes around the namespace_prefix."
        echo ""
        display_syntax
        exit
    fi
}

function makeDirectories(){
    echo "Make Directories"
    echo "================"
    mkdir -p ${namespace_prefix_lowerfirstchar}/Facades
    mkdir -p ${namespace_prefix_lowerfirstchar}/Providers
    mkdir -p ${namespace_prefix_lowerfirstchar}/Facades
}

function createSourceTemplate(){
    source_template=$(echo "${source_template}" | sed -e 's/{namespace_prefix}/'${namespace_prefix}'/g' -e 's/{facade_name_upcase}/'${facade_name_upcase}'/g' -e 's/{facade_name_lowercase}/'${facade_name_lowercase}'/g')
    echo "Create Source Template:"
    echo "======================="
    echo "${source_template}"
    echo ""
    echo "${source_template}" > ./${namespace_prefix_lowerfirstchar}/Facades/${facade_name_upcase}.php
}

function createServiceProviderTemplate(){
    serviceProvider_template=$(echo "${serviceProvider_template}" | sed -e 's/{namespace_prefix}/'${namespace_prefix}'/g' -e 's/{facade_name_upcase}/'${facade_name_upcase}'/g' -e 's/{facade_name_lowercase}/'${facade_name_lowercase}'/g')
    echo "Create ServiceProvider Template:"
    echo "================================"
    echo "${serviceProvider_template}"
    echo ""
    echo "${serviceProvider_template}" > ./${namespace_prefix_lowerfirstchar}/Providers/${facade_name_upcase}ServiceProvider.php
}

function createFacadeTemplate(){
    facade_template=$(echo "${facade_template}" | sed -e 's/{namespace_prefix}/'${namespace_prefix}'/g' -e 's/{facade_name_upcase}/'${facade_name_upcase}'/g' -e 's/{facade_name_lowercase}/'${facade_name_lowercase}'/g')
    echo "Create Facade Template:"
    echo "======================="
    echo "${facade_template}"
    echo ""
    echo "${facade_template}" > ./${namespace_prefix_lowerfirstchar}/Facades/${facade_name_upcase}Facade.php
}


function serviceProviderPrompt(){
    echo "Providers: ${namespace_prefix_in}\Providers\\${facade_name_upcase}ServiceProvider,"
}

function aliasPrompt(){
    echo "Alias: '"${facade_name_upcase}"' => '"${namespace_prefix_in}"\Facades\\${facade_name_upcase}Facade'," 
}

#
#   END FUNCTION DECLARATIONS
#


###########################
## START RUNNING SCRIPT  ##
###########################

display_start_banner

init_and_export_vars
makeDirectories 
checkDirectoryExists
echo ""

createSourceTemplate
createServiceProviderTemplate
createFacadeTemplate
echo ""
echo "==========================="
echo "  Finished TEST"
echo "==========================="
echo ""
echo "Add these lines to config/app.php:"
echo "----------------------------------"
serviceProviderPrompt
aliasPrompt
echo ""

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: 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

19 upvote
  flag
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
1 upvote
  flag
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. – MaXi32
upvote
  flag
@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
upvote
  flag
@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: //allinonescript.com/questions/28290332/… – heisian
upvote
  flag
@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.) – Dan Hunsaker
upvote
  flag
@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. – heisian
1 upvote
  flag
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. – Dan Hunsaker
upvote
  flag
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. – heisian
upvote
  flag
This works well. But should it be /config/app.php not /app/config.php (Step 2) – P_95
upvote
  flag
@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 – goredwards
upvote
  flag
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? – stef
upvote
  flag
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() { – omarjebari
upvote
  flag
Wouldn't that 'Use helper' throw an The use statement with non-compound name 'Helper' has no effect in... ? – FabioCosta
upvote
  flag
This answer was written for Laravel 5.1, feel free to propose any edits for the latest version.. I haven't used it yet. – heisian

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>
upvote
  flag
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
1 upvote
  flag
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! – heisian
1 upvote
  flag
I find this to be a the best of all – Jimmy Obonyo Abor
upvote
  flag
Why is there extends Helper? It doesn't seem necessary for me. – bernie
upvote
  flag
@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. – dKen
upvote
  flag
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. – Andrew Brown
upvote
  flag
@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. – dKen
upvote
  flag
@AndrewBrown there are no Facades here - just php static methods. Essentially namespaced functions. I agree that Facades are a ridiculous nonstandard obfuscation though. – Rick Jolly
upvote
  flag
@AndrewBrown this is not a facade. This is PSR-4 autoloading. php-fig.org/psr/psr-4 – heisian
upvote
  flag
@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. – heisian

For Custom Helper Libraries in my Laravel project, I have created a folder with name Libraries in my Laravel/App Directory and within Libraries directory, I have created various files for different helper libraries.

After creating my helper files I simply include all those files in my composer.json file like this

...
"autoload": {
        "classmap": [
            "database"
        ],
        "files": [
            "app/Libraries/commonFunctions.php"
        ],
        "psr-4": {
            "App\\": "app/"
        }
    },
...

and execute

composer dumpautoload
upvote
  flag
composer dump-autoload and composer dumpautoload also works infact composer du will also work... – Akshay Khale

Custom Blade Directives in Laravel 5

Yes, there is another way to do this!

Step 1: Register a custom Blade directive:

<?php // code in app/Providers/AppServiceProvider.php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

use Blade; // <-- This is important! Without it you'll get an exception.

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
     public function boot()
     {
         // Make a custom blade directive:
         Blade::directive('shout', function ($string) {
             return trim(strtoupper($string), '(\'\')');
         });

         // And another one for good measure:
         Blade::directive('customLink', function () {
             return '<a href="#">Custom Link</a>';
         });
     }
    ...

Step 2: Use your custom Blade directive:

<!-- // code in resources/views/view.blade.php -->

@shout('this is my custom blade directive!!')
<br />
@customLink

Outputs:

THIS IS MY CUSTOM BLADE DIRECTIVE!!
Custom Link


Source: https://laravel.com/docs/5.1/blade#extending-blade

Additional Reading: https://mattstauffer.co/blog/custom-conditionals-with-laravels-blade-directives


If you want to learn how to best make custom classes that you can use anywhere, see Custom Classes in Laravel 5, the Easy Way

Another Way that I used was: 1) created a file in app\FolderName\fileName.php and had this code inside it i.e

<?php
namespace App\library
{
 class hrapplication{
  public static function libData(){
   return "Data";
  }
 }
}
?>

2) After that in our blade

 $FmyFunctions = new \App\FolderName\classsName;
  echo $is_ok = ($FmyFunctions->libData());

that's it. and it works

In laravel 5.3 and above, the laravel team moved all procedural files (routes.php) out of the app/ directory, and the entire app/ folder is psr-4 autoloaded. The accepted answer will work in this case but it doesn't feel right to me.

So what I did was I created a helpers/ directory at the root of my project and put the helper files inside of that, and in my composer.json file I did this:

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

This way my app/ directory is still a psr-4 autoloaded one, and the helpers are a little better organized.

Hope this helps someone.

in dir bootstrap\autoload.php

require __DIR__.'/../vendor/autoload.php';
require __DIR__.'/../app/Helpers/function.php'; //add

add this file

app\Helpers\function.php

Best Practice to write custom helpers is

1) Inside the app directory of the project root, create a folder named Helpers (Just to separate and structure the code).

2) Inside the folder write psr-4 files or normal php files

If the PHP files are in the format of psr-4 then it will be auto loaded, else add the following line in the composer.json which is inside the project root directory

Inside the autoload key, create a new key named files to load files at the time of auto load,inside the files object add the path starting from app directory., here is an example.

"autoload": {
    "classmap": [
        "database"
    ],
    "psr-4": {
        "App\\": "app/"
    },
    "files": [
        "app/Helpers/customHelpers.php"
    ]
},
"autoload-dev": {
    "classmap": [
        "tests/TestCase.php"
    ]
},

PS : try running composer dump-autoload if the file dosen't loaded.

Since OP asked for best practices, I think we're still missing some good advices here.

A single helpers.php file is far from a good practice. Firstly because you mix a lot of different kind of functions, so you're against the good coding principles. Moreover, this could hurt not only the code documentation but also the code metrics like Cyclomatic Complexity, Maintainability Index and Halstead Volume. The more functions you have the more it gets worse.

Code documentation would be Ok using tools like phpDocumentor, but using Sami it won't render procedural files. Laravel API documentation is such a case - there's no helper functions documentation: https://laravel.com/api/5.4

Code metrics can be analyzed with tools like PhpMetrics. Using PhpMetrics version 1.x to analyze Laravel 5.4 framework code will give you very bad CC/MI/HV metrics for both src/Illuminate/Foundation/helpers.php and src/Illuminate/Support/helpers.php files.

Multiple contextual helper files (eg. string_helpers.php, array_helpers.php, etc.) would certainly improve those bad metrics resulting in an easier code to mantain. Depending on the code documentation generator used this would be good enough.

It can be further improved by using helper classes with static methods so they can be contextualized using namespaces. Just like how Laravel already does with Illuminate\Support\Str and Illuminate\Support\Arr classes. This improves both code metrics/organization and documentation. Class aliases could be used to make them easier to use.

Structuring with classes makes the code organization and documentation better but on the other hand we end up loosing those great short and easy to remember global functions. We can further improve that approach by creating function aliases to those static classes methods. This can be done either manually or dynamically.

Laravel internally use the first approach by declaring functions in the procedural helper files that maps to the static classes methods. This might be not the ideal thing as you need to redeclare all the stuff (docblocks/arguments).
I personally use a dynamic approach with a HelperServiceProvider class that create those functions in the execution time:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class HelperServiceProvider extends ServiceProvider
{
    /**
     * The helper mappings for the application.
     *
     * @var array
     */
    protected $helpers = [
        'uppercase' => 'App\Support\Helpers\StringHelper::uppercase',
        'lowercase' => 'App\Support\Helpers\StringHelper::lowercase',
    ];

    /**
     * Bootstrap the application helpers.
     *
     * @return void
     */
    public function boot()
    {
        foreach ($this->helpers as $alias => $method) {
            if (!function_exists($alias)) {
                eval("function {$alias}(...\$args) { return {$method}(...\$args); }");
            }
        }
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

One can say this is over engineering but I don't think so. It works pretty well and contrary to what might be expected it does not cost relevant execution time at least when using PHP 7.x.

There are some great answers here but i think this is the simplest. In Laravel 5.4 (and prob earlier versions too) you can create a class somewhere convenient for you, eg App/Libraries/Helper.php

class Helper() {
    public function uppercasePara($str) {
        return '<p>' .strtoupper($str). '<p>;
    }
}

Then you can simply call it in your Blade template like this:

@inject('helper', \App\Libraries\Helper)
{{ $helper->drawTimeSelector() }}

If you don't want to use @inject then just make the 'uppercasePara' function as static and embed the call in your Blade template like this:

{{ \App\Libraries\Helper::drawTimeSelector() }}

No need for aliases. Laravel resolves the concrete class automatically.

Create custom helpers’ directory: First create Helpers directory in app directory. Create hlper class definition: Let’s now create a simple helper function that will concatenate two strings. Create a new file MyFuncs.php in /app/Helpers/MyFuncs.php Add the following code

<?php

namespace App\Helpers;

class MyFuncs {

    public static function full_name($first_name,$last_name) {
        return $first_name . ', '. $last_name;   
    }
}

namespace App\Helpers; defines the Helpers namespace under App namespace. class MyFuncs {…} defines the helper class MyFuncs. public static function full_name($first_name,$last_name) {…} defines a static function that accepts two string parameters and returns a concatenated string

Helpers service provide class

Service providers are used to auto load classes. We will need to define a service provider that will load all of our helper classes in /app/Helpers directory.

Run the following artisan command:

php artisan make:provider HelperServiceProvider

The file will be created in /app/Providers/HelperServiceProvider.php

Open /app/Providers/HelperServiceProvider.php

Add the following code:

<?php 

namespace App\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);
        }
   }
}

HERE,

namespace App\Providers; defines the namespace provider
use Illuminate\Support\ServiceProvider; imports the ServiceProvider class namespace
class HelperServiceProvider extends ServiceProvider {…} defines a class HelperServiceProvider that extends the ServiceProvider class
public function boot(){…} bootstraps the application service
public function register(){…} is the function that loads the helpers
foreach (glob(app_path().'/Helpers/*.php') as $filename){…} loops through all the files in /app/Helpers directory and loads them.

We now need to register the HelperServiceProvider and create an alias for our helpers.

Open /config/app.php file

Locate the providers array variable

Add the following line

App\Providers\HelperServiceProvider::class,

Locate the aliases array variable

Add the following line

'MyFuncs' => App\Helpers\MyFuncs::class,

Save the changes Using our custom helper

We will create a route that will call our custom helper function Open /app/routes.php

Add the following route definition

Route::get('/func', function () {
    return MyFuncs::full_name("John","Doe");
});

HERE,

return MyFuncs::full_name("John","Doe"); calls the static function full_name in MyFuncs class

First create helpers.php inside App\Http directory. Then add the following code inside the composer.json

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

Next run the following command

composer dump-autoload

Now you can define your custom function inside the helpers.php file. Here you can get the full guide

Create Helpers.php in app/Helper/Helpers.php namespace App\Helper class Helpers {

}

Add in composer and composer update

 "autoload": {
        "classmap": [
            "database/seeds",
            "database/factories",
            "database","app/Helper/Helpers.php"
        ],
        "psr-4": {
            "App\\": "app/"
        },
         "files": ["app/Helper/Helpers.php"]
    },

use in Controller

use App\Helper\Helpers
upvote
  flag
Thank you, would you mind expanding a bit on your explaination? – Felipe Valdes

instead of including your custom helper class, you can actually add to your config/app.php file under aliases.

should be look like this.

 'aliases' => [ 
    ...
    ...
    'Helper' => App\Http\Services\Helper::class,
 ]

and then to your Controller, include the Helper using the method 'use Helper' so you can simply call some of the method on your Helper class.

eg. Helper::some_function();

or in resources view you can directly call the Helper class already.

eg. {{Helper::foo()}}

But this is still the developer coding style approach to be followed. We may have different way of solving problems, and i just want to share what i have too for beginners.

I disagree with every other answer to this question!

Firstly, there is nothing wrong with having a few global helper functions. By way of example, the application I'm currently working on is five years old (it started on Laravel 3!) and has a total of just six global functions that are used frequently for date formatting and debugging purposes. There are no clashes with any other functions in the global namespace and, at their core, they are not object-oriented, so why make them static methods in a container class? One thing that I believe is worse than relying too heavily on plain old functions is packaging them up as classes and deluding yourself into thinking that you are now doing things The Right Way. Also, having to prefix these helper functions with a class name or class alias is just horribly painful, hence my preference to keep them as simple global functions.

Secondly, if we want to talk about code purity, we should not consider a solution that drops a helpers.php file anywhere in the app/ area, as the app/ folder is meant to be for PSR-4 classes only.

Also, I think many of the answers are just way too complicated. Creating new provider classes just to autoload a bunch of other code when there is already a perfectly good place to autoload code is just silly.

I only noticed one answer that considered modifying bootstrap/autoload.php, which, in my opinion, is absolutely the most appropriate place to hook in. There is no rule, written or otherwise, that says we shouldn't change this file. Sure, you need to check if it changes from one Laravel release to the next, but the same goes for config files, provider classes, queuing stuff, etc.

Therefore, I believe the simplest, most appropriate solution is to create a file in the bootstrap folder called helpers.php and add the following line to the end of boostrap/autoload.php:

require __DIR__.'/helpers.php';

That other answer that suggested changing autoload.php was almost the perfect answer (IMO), except they suggested putting function.php in the app/Helpers folder. As mentioned above, the app/ folder is meant to be for PSR-4 classes, so not the best place to throw a file with a bunch of helper functions.

Not the answer you're looking for? Browse other questions tagged or ask your own question.