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

prasoon1960's avatar

Helper in laravel

I would like to create helper functions to avoid repeating code between views in Laravel 5:

view.blade.php

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

They're basically text formatting functions. Where and how can I create a file with these functions?
0 likes
8 replies
Nakov's avatar

@prasoon1960 you can create a php file in the app directory let's say helpers.php

In it add this:

<?php

function test() {
    return '';
}   

Then in your composer.json in the autoload object add this

"autoload": {
...
        "files": [
            "app/helpers.php"
        ],
    },

and run composer dump-autoload

Now the test() will be available in the view and in controllers.

hitesh399's avatar

@nakov , the way to load helper file is correct, But I will suggest to use a class instead of helper function. Because if you define a file under auto-load, then file loads in every request, So it will be good create folder in app dir like:

app -> Lib and make a helper class like:

namespace App\Lib

class Helper { // Write your method here... }

use App\Lib;

$helper = new Helper()

Nakov's avatar

@hitesh399 I would agree, but the functions are just being loaded as there are hundreds of other helper files. I've been using this method, and haven't felt any performance issues. :)

Using your approach is okay, but anytime the function needs to be used, an object needs to be passed to the view, which does not makes the process easy :)

hitesh399's avatar

@nakov , As you can see in laravel latest version, Laravel has been removed some helper functions. So I think, To use class instead of function is Good way.

jlrdw's avatar

I usually just have static helpers

<?php

namespace App\Helpers;

use Illuminate\Support\Facades\Session;
use App\Helpers\Url;
use Illuminate\Support\Facades\Auth;


class Clnsantize
{
    public static function fixValue($rvalue)
    {
        $rvalue = empty($rvalue) && !is_numeric($rvalue) ? NULL : trim(strip_tags($rvalue));
        return $rvalue;
    }


///// more methods

Or if you insist on instance, you can use __callStatic(), or in laravel make a facade, which just uses __callStatic() anyway.

I just have a use statement

use App\Helpers\Clnsantize as Cln;

And usage

$dogpic = Cln::fixValue($newname);
hemmy6894's avatar

Create you helper

<?php
namespace App\Http\Helpers;

class Display{
    public static function foo($text){
        echo $text;
    }
}

go in config/app.php

add your helper in aliases

...
 'aliases' => [
    .....
    'Helper' => 'App\Http\Helper\Display',
    ...
    ],
...

go to you view

    .....
    <div>
        {{ Helper::foo("hey prasoon1960") }}
    </div>
    ...

Please or to participate in this conversation.