Huligan
Huligan

Reputation: 429

How create own class helper in Laravel?

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?

Upvotes: 2

Views: 117

Answers (3)

Rahul Hirve
Rahul Hirve

Reputation: 1139

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.

Upvotes: 0

vijaykumar
vijaykumar

Reputation: 4806

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.

Upvotes: 1

Altimir Antonov
Altimir Antonov

Reputation: 5056

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

Upvotes: 3

Related Questions