Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

calebeoliveira's avatar

Best practices for custom helpers on Laravel 5

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

Formated text: {{ fooFormatText($text) }}

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

0 likes
37 replies
JeffreyWay's avatar
  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.

That should do it. :)

154 likes
bestmomo's avatar

@menieass

If your composer "files" autoload option is correct you should find your reference in vendor/composer/autoload_files.php. Check it.

pmall's avatar

You can also include the helper file in the boot method of your AppServiceProvider

racl101's avatar

Just tried Jeffrey's way (no pun intended) and it worked for me on Laravel 5.

8 likes
stefanbauer's avatar

Another question to that related topic. Is there a rule when to use easy "php"-helpers like in the above examples, or when to create a blade extension? Both would end in the same result. But is there something when to do what?

luanrodriguesp's avatar

I did the same way that @JeffreyWay said and i'm getting "Call to undefined function"

here is my helpers.php


php namespace App\Http;
class Helpers {
    public function FixData($data){
        $d = explode("-", $data);
        return $d[2]."/".$d[1]."/".$d[0];
    }
}

OBS: To post here, I have removed the "<\?" from the first line, but in the original file its ok.
alanablett's avatar

@luanrodriguesp

Jeffs method includes a file containing functions only, not a class. SO your file should look like this:

public function FixData($data){
    $d = explode("-", $data);
    return $d[2]."/".$d[1]."/".$d[0];
}
4 likes
bestmomo's avatar

@luanrodriguesp if you want to use classes you can create a service in app/Services with good namescpace and it'll be autoloaded.

1 like
martinbean's avatar

@stefanbauer What if you need to use a helper outside of a Blade template? What if you switch your template engine? You then have to re-write your Blade extensions into whatever template engine you’re switching to.

tjans's avatar

I was getting the same undefined error until I RTFM, and instead of adding the files piece to the bottom, I added it to the autoload block as the instructions said and voila, it worked!

Vasek18's avatar

Did everything like Jeffrey said, but still got "Call to undefined function" Laravel 5.2 From composer: "autoload": { "classmap": [ "database" ], "psr-4": { "App\": "app/" }, "files": [ "app/helpers.php" ] },

From autoload_files.php: 'b4e3f29b106af37a2bb239f73cdf68c7' => $baseDir . '/app/helpers.php',

Update The problem was in php brackets. I used <? instead of <?php

donpuerto's avatar

@vasanth it should work, take note, you will allow only function.

yes

function ($x, $y){
    //return blah blah;
}

no

public function ($x, $y){
    //return blah blah;
}
5 likes
Bespired's avatar

In app/Http/helpers.php

<?php

function str_spacecase($slug)
{

    return str_replace("_", " ", $slug);

}

in app/Providers/AppServiceProvider.php

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
        require_once __DIR__ . '/../Http/helpers.php';
    }
}
16 likes
royshay's avatar

@Bespired - Does this then mean I need to do a \App\Http\doSomething(); whenever I need to call that method? Because I can't get this to work any other way...

martinbean's avatar

@calebeoliveira You can follow Laravel’s approach and create a file at app/Support/helpers.php. You will need to add this to the autoload section of your composer.json file:

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

Then your helpers.php file should look like this:

<?php

if (! function_exists('fooFormatText')) {
    /**
     * Format text.
     *
     * @param  string  $text
     * @return string
     */
    function fooFormatText($text)
    {
        // Format text
        return $text;
    }
}
2 likes
mirzavu's avatar

@martinbean This method works in my localhost , but the file is not loaded by composer in my remote server. In server , when I checked vendor/composer/autoload_files.php I see the file is not listed here.

lindstrom's avatar

Don't forget about accessors/mutators if you are truly thinking about formatting some field you get from a model. For example I wouldn't format a phone number with a helper, I'd do it right on the model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Customer extends Model
{
    public function getPhoneNumberAttribute($value)
    {
        return preg_replace('/([0-9]{3})([0-9]{3})([0-9]{4})/','$1-$2-$3',$value);
    }

}

And when you later need to store the value:

public function setPhoneNumberAttribute($value)
{
    $value = preg_replace('/\D/', '', $value);
}

By using the accessor on the model, you don't have to even think about a helper for formatting.

1 like
DaniloSantosDev's avatar

@JeffreyWay and everybody,

If i want to retrieve some values in my database and access the cache using the facades, is it possible with this approach?

Thanks!

guitar-freq's avatar

Hi all,

Thanks for all the info. I have tried literally EVERYTHING here and nothing allows me to access functions in app/helper/helper.php from app/Jobs/myJob.php (or any other directory under app). helper.php is not a class just a file with functions in it. It sees the helper functions if I'm in app/Http/Controllers/myController.php.

I've tried require. I have the "files" entry in autoload block and ran composer dump-autoload. I verified the entry is in the autoload file. I've tried various use entries from the calling file.

Nothing works and all return "Call to undefined function". If anyone has suggestions, including how I should call the function, please let me know.

Thank you!

DaniloSantosDev's avatar

@guitar-freq I followed the instructions and works for me.

i'll try to explain what i've done.

I created a file in "app/Support/helpers.php" with a basic structure like this:

<?php

    // something here
    function something(){
        return true;
    }

?>

In my "composer.json" file i added a reference to "helpers.php" in the "files" options and then run "composer dump-autoload" to Laravel see the changes.

Like this:


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

That's it!

After this, i can access the "something" function in my blades, repositories, services, etc.

I hope you got it. Hugs.

aaronranard's avatar

In case someone wants a solution that doesn't involve changing composer.json, here's what I did.

create a new folder Helpers and add file app/Helpers/custom.php

<?php

namespace App\Helpers;

class Custom
{
    public static function getUrl()
    {
      return 'fancy logic';
    }
}

then in config/app.php add to the aliases array 'Custom' => App\Helpers\Custom::class,

then in your view you can simply use the Custom facade like

{{ Custom::getUrl() }}

2 likes
Bespired's avatar

@PhongLeHong

Another option is to create a HelperServiceProvider for it.

artisan make:provider HelperServiceProvider

Within the register method add this snippet

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

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

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

Put your helpers in app/Helpers/

1 like
Bespired's avatar

@royshay

As far as I know helpers are functions defined in global namespace.

Take a look at Laravel helpers to see that they are not in a Class. /vendor/laravel/framework/src/Illuminate/Foundation/helpers.php

Artistan's avatar

helpers defined in the global namespace will cause more issues if/when you include other packages that also define function in the global namespace.

Please don't do this!

I like @Bespired example of the HelperServiceProvider. properly namespaced helpers should Rarely cause any issues.

Adeguk's avatar

I had tried all the above including that suggested by @Bespired, the only time any of them work is when I add the relative link to the function as:

\App\Support\humanize_date();

this is my code

if ( !function_exists('humanize_date')) {
   function humanize_date(Carbon\Carbon $date, $format = 'd F Y, H:i'):string
   {
       return $date->format($format);
    }
 }

I am calling the function in view layout.

Next

Please or to participate in this conversation.