How to Create Custom Helper in Laravel 9? | Helper Function

Configuration of Custom Helper in Laravel

The helper file needs to autoload after created. Then configuration will be performed in the helper file. So let's understand how to do this work. Create helper.php inside apps. The path will be apps>helper.php.
You can choose any name for this file like CustomHelper.php, Include.php and Autoload.php. I prefered here helper.php.
I have written hello inside helper.php to test it.

<!--php

// Important functions

echo "Hello";
?-->

Now autoload to this helper. Go to composer.json create an array named "files" = [] in the autoload and give the path of helper file like given below.

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

Now autoload with the help of command. Open new terminal and type:

composer dump-autoload


This command resets all the settings of composer that's why composer is able to include helper file.

Now the hello text will be visible on the all pages
We can create functions in helper and reuse them again and again like:

if(!function_exists('p')){
    function p($data){
        echo "<pre>";
        print_r($data);
        echo "</pre>";
    }
}


if(!function_exists('get_formatted_date')){
    function get_formatted_date($date, $format){
        $formattedDate = date($format, strtotime($date));
        return $formattedDate;
    }
}

Use of above functions are given below:

public function store(Request $request){
    p($request->all());

@foreach ($customers as $customer)
<tr class="">
    <td>{{$customer->name}}</td>
    <td>{{$customer->email}}</td>
    <td>
        @if ($customer->gender == "M")
            Male
        @elseif($customer->gender == "F")
            Female
        @else
            Other
        @endif
    </td>
    <td>{{$customer->state}}</td>
    <td>{{$customer->city}}</td>
    <td>{{$customer->address}}</td>
    <td>{{get_formatted_date($customer->dob, 'd-M-Y')}}</td>
    <td>
        @if ($customer->status == "1")
            <span class="badge bg-success">Active</span>
        @else
            <span class="badge bg-danger">Inactive</span>
        @endif
    </td>
    <td>
        <a href="{{Route(&#39;customer.delete&#39;, [&#39;id&#39; =&gt; $customer-&gt;customer_id])}}"><button class="btn btn-danger">Delete</button></a>
        <a href="{{Route(&#39;customer.edit&#39;, [&#39;id&#39;=&gt; $customer-&gt;customer_id])}}"><button class="btn btn-primary">Edit</button></a>
    </td>
</tr>
@endforeach

Comments