Nicolas
Nicolas

Reputation: 371

Add your own helpers.php to composer.json

Following this topic Use a custom function everywhere in the website I need a bit of help to finish what has been started.

So I created a folder in the app folder: Customs Then I created a helpers.php file that has the following code:

<?php
use Illuminate\Support\Str;

if (! function_exists('str_slug')) {
    /**
     * Generate a URL friendly "slug" from a given string.
     *
     * @param  string  $title
     * @param  string  $separator
     * @return string
     */
    function my_slug($title, $separator = '-')
    {
        $title = str_replace('\'','_',$title);
        return Str::slug($title, $separator);
    }
}

I read that I now have to update my composer.json, and especially the autoload section which is basically:

"autoload": {
        "classmap": [
            "database"
        ],
        "psr-4": {
            "App\\": "app/"
        }
    },

I don't understand what I should do now... psr-4 already says that the whole app folder is autoloaded, no?

I also tried to put the full path to the helpers.php but it did not work either.

What am I doing wrong?

Upvotes: 3

Views: 2231

Answers (3)

futureweb
futureweb

Reputation: 442

  • Use it in your view: {{my_slug($collection->value)}} or

  • in your controllers with the namespacing App\customs\my_slug($value) or

  • by adding use \App\customs to the top of your controller and then my_slug($value).

Upvotes: 0

manix
manix

Reputation: 14747

  1. Create a folder inside of app/ called Helpers.
  2. Inside of app/Helpers create your custom class

    namespace App\Helpers;
    
    class FooHelper{
    
        public static function bar(){
            return 'bar';
        }
    }
    
  3. Run composer dump-autoload to update autoload.

Here you are now able to use your helper functions like:

$bar = \App\Helper\FooHelper::bar();

If your plan is attach a facade, then edit facades array in config/app.php like so:

'Foo' => \App\Helpers\FooHelper::class

Now you can call your functions like:

public function controllerFunction(){
    $bar = \Foo::bar();
}

Upvotes: 2

Grzegorz Gajda
Grzegorz Gajda

Reputation: 2474

Your autoload should have something like that:

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

where files are your custom files. Also as is mentioned in Use a custom function everywhere in the website question I advice you to use traits for e.g. trait StringSluggify. It keeps OOP way.

Upvotes: 7

Related Questions