Skip to content

Custom Helper functions in Laravel

Last updated on January 30, 2021

In this post, we gonna create custom functions and load it in the Laravel project. These functions can be accessible all over the project. Loading custom helper functions in Laravel is pretty straightforward. Let’s follow the below steps,

First, create a file called TextHelper.php the filename can be anything, and place your custom functions in the file. Depending on your preference, you can organize the location of your helper file(s) however you want, however, we gonna create a folder called Helpers in the app folder, inside this folder we will place helper(s).

// app/Helpers/TextHelper.php
function the_excerpt($content) {
    return Str::of(strip_tags($content))->words($words = 20, $end='...');
}

Now you have to load this helper file so that the helper function will be available in the project. So in order to load the helper file, update your composer.json file autoload section as shown below.

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

We just added a files key to autoload object and files key holds an array of file paths. Now you need to dump the autoloader with below compose command

composer dump-autoload

Now you can use the the_excerpt() function in your laravel project.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments