10

I've read a lot of questions on how to make helper methods in Laravel 5.1. But I don't want to achieve this via a Facade.

HelperClass::methodName();

I want to make helper methods just like on these methods Laravel Helper Methods like:

myCustomMethod();

I don't want to make it a Facade. Is this possible? How?

2
  • You want to make a custom function like array_add()? Commented May 20, 2016 at 6:36
  • @RobinDirksen Yes Sir. You got it. Commented May 20, 2016 at 6:37

3 Answers 3

7

If you want to go the 'Laravel way', you can create helpers.php file with custom helpers:

if (! function_exists('myCustomHelper')) {
    function myCustomHelper()
    {
        return 'Hey, it\'s working!';
    }
}

Then put this file in some directory, add this directory to autoload section of an app's composer.json:

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

Run composer dumpauto command and your helpers will work through all the app, like Laravel ones.

If you want more examples, look at original Laravel helpers at /vendor/laravel/framework/Illuminate/Support/helpers.php

Sign up to request clarification or add additional context in comments.

Comments

6

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',
]

After that you need to run composer dump-autoload and your changes will be visible in Laravel.

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

Hope this works!

Comments

0

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

Within your app/Http directory, create a helpers.php file and add your functions.

Within composer.json, in the autoload block, add "files": ["app/Http/helpers.php"]. And run

composer dump-autoload.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.