Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 682
Nicolas Lemoine Avatar asked Dec 07 '25 01:12

Nicolas Lemoine


1 Answers

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.

like image 85
Grzegorz Gajda Avatar answered Dec 08 '25 14:12

Grzegorz Gajda



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!