poashoas
poashoas

Reputation: 1894

Laravel organize helper functions

Please, don't talk to technical in the answers:-D I am not a hardcore programmer.

What is a good way to store certain functions in Laravel? I have functions that apply on a "post" only or "media" only, like getAttributeList or getComponents. I say "Post" and "Media" because both have their own controller, model and views. It feels wrong to put it in the model because that should be database stuff right? And traits are more for recurring functions all over the place, right? So, right now I have one big file called Helpers.php. And uh, it is getting large... should I simply separate it in PostHelpers.php, MediaHelpers.php etc? Or is there a more elegant way in Laravel to do it?

Upvotes: 3

Views: 465

Answers (2)

Shivam Trivedi
Shivam Trivedi

Reputation: 71

It is quite simple : Just check your composer.json file at root directory of ur app. and under autoload section add :

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

"files": ["app/helper.php"], This is the line you need to add in ur composer file and provide the path to file . In my case i have created a file helper.php in App directory where i keep all my functions . after this run this command : composer dump-autoload

Now u can access your functions anywhere.

Upvotes: 1

BlackXero
BlackXero

Reputation: 880

In your composer json file check this snippet

"autoload": {
        "files": [
                "app/Helpers/global_helper.php"
            ],

As you see I have auto loaded 1 single file called global_helper.php in a folder called Helpers Now in this file I have a function called loadHelper(...$files) What this function does is

if (!function_exists('loadHelper')) {
    function loadHelper(...$file_names)
    {
        foreach ($file_names as $file) {
            include_once __DIR__ . '/' . $file . '_helper.php';
        }
    }
}

You can pass your file name as array or string and it will include those files into your Controller constructor

So In my Controller whenever I want some helper function I create a saperate helper file for that controller then in constructor i ust include it.

I am not sure if there is any better solution but so far this is how I am making all my projects .

I hope this will help you ;)

Upvotes: 0

Related Questions