2

I need to create own class with methods, that I want to call from diverse controllers.

What it should be: Library, Provider or Helper in Laravel?

0

3 Answers 3

3

1: Create folder app/Helpers
2: In app/Providers create new provider file HelperServiceProvider.php
3: In this file register all helpers classes you need

$this->app->bind('dateHelper', function()
{
    return new \App\Helpers\DateHelper;
});
... etc

4: In config/app.php add this new provider

'App\Providers\HelperServiceProvider', 

5: Then you need to create Facade to be available to use this helper in view. You find the info about how to create Facade on official laravel.com site


About the providers, you can read the doc
Source: Laravel Forums

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

1 Comment

Can you explain how to use helper class in controller?
1

You can do this in many ways

  1. Static way

    • Create a folder your wish Utils or Helpers or Libraries.

    • Create a Class (ex: Helper Class)

    • Added static methods here (ex: public static common()).

    • Added namespace to the call.

    • Use the name space and call the static function using(Helper::common)

  2. Normal Class

    • Create class with name space.
    • Inject the Dependency of that class and use all function inside.

Comments

0

You can follow the simple steps below

  • Step 1

    Create new helper file in app/Helpers directory Ex. I have created the DemoHelper.php in directory app/Helpers/DemoHelper.php

  • Step 2

    Add the entry of created Helper(DemoHelper.php) to composer.json file in autoload section

    "autoload": {
     "files": [
         "app/Helpers/Helper.php",
         "app/Helpers/DemoHelper.php"
     ]
    },
    
  • Step 3

    Finaly, composer dump-autoload hit this command in terminal.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.