DEV Community

Techsolutionstuff
Techsolutionstuff

Posted on • Originally published at techsolutionstuff.com

How To Create Custom Helper Function In Laravel 9

In this article, we will see how to create a custom helper function in laravel 9. As we all know laravel provides many in-built helper functions in their framework, but many times we need to require our own customized function to use in our project that time we need to create a custom helper function in laravel 9.

So, here I will give you a custom helper function example in laravel 9.

So, let's see the custom helper function in laravel 9 and laravel 9 custom helper functions.

Laravel includes a variety of global helper PHP functions like Arrays, paths, strings, URLs, etc. So, you can use these functions as per your requirements.

Step 1: Create helpers.php File
In this step, we will create the app/helpers.php file in our laravel project and add the below code.

app/helpers.php

<?php

function Date_Format($date,$format){
    return \Carbon\Carbon::createFromFormat('Y-m-d', $date)->format($format);    
}

?>
Enter fullscreen mode Exit fullscreen mode

Read Also: How To Connect Multiple Database In Laravel 9


Step 2: Add Helper File Path In composer.json File

Add the below code in the composer.json file.

"autoload": {
        "psr-4": {
            "App\\": "app/",
            "Database\\Factories\\": "database/factories/",
            "Database\\Seeders\\": "database/seeders/"
        },
         "files": [
            "app/helpers.php"
        ]
    },
Enter fullscreen mode Exit fullscreen mode

Step 3: Run Command

Now, run the below command in your terminal

composer dump-autoload
So, we are done with the custom helper function in laravel 9, as of now we can use this function anywhere across applications.

Here I am using this function in the blade file.

<html>
 <head>
     <meta charset="utf-8">
     <meta http-equiv="X-UA-Compatible" content="IE=edge">
     <title>How To Create Custom Helper Function In Laravel 9 - Techsolutionstuff</title>
     <link rel="stylesheet" href="">
 </head>
 <body>
    <h3>How To Create Custom Helper Function In Laravel 9 - Techsolutionstuff</h3>
     <h3>New Date Format: {{ Date_Format('2022-02-26','m/d/Y')  }}</h3>
 </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Read Also: How To Image Upload With Preview In Laravel 9


Output :

New Date Format: 02/26/2022
Enter fullscreen mode Exit fullscreen mode

You might also like:

Top comments (1)

Collapse
 
happymacarts profile image
happymacarts

How would you use these helpers in a controller or model file?