How to create Custom Laravel Helpers in Laravel 9

What is Laravel Helpers?

Laravel includes a variety of global “helper” PHP functions. Many of these functions are used by the framework itself; however, you are free to use them in your own applications if you find them convenient.

Also Read : How to Send Email using PHPMailer in Laravel 9

You can find the lists of helpers Available Methods in laravel website.

Sometime you have to create your own helper function for your website.

So, Today we are going to learn how you can create your own helper function in laravel 9.

Step for Creating Laravel 9 Custom Laravel Helpers

  • Step 1 : Create Custom Helpers File
  • Step 2 : Config Helpers File in Laravel
  • Step 3 : Calling Custom Helpers File Function
  • Step 4 : Example

Step 1 : Create Custom Laravel Helpers File

First you have to create a folder inside app/ and call it Helpers there you have to create a file name Helpers.php inside Helpers folder.

Add the following code inside the app/Helpers/Helpers.php file

<?php
 
namespace App\Helpers;
 
class Helpers {
 
    public static function this_is_your_function()
    {
    // Add function codes hear or do something
    // Laravel Custom Helpers
    }
}

Also Read : Laravel 9 – Drag and Drop file upload using Dropzone

Step 2 : Config Helpers File in Laravel

Inorder to access this helpers file globally we have to autoload it. To autoload the file we have to create new aliases in config file.

To add a new aliases goto config/app.php file. All the following line into app.php.

'Helpers' => App\Helpers\Helpers::class,

Step 3 : Calling Custom Helpers File Function 

Now you can call your custom helper function anywhere in your application as below.

Helper::this_is_your_function()

Also Read : How to install Selectize.JS in Laravel 9

Step 4 : Example

Function:

<?php // Code within app\Helpers\Helper.php

namespace App\Helpers;

class Helpers
{
    public static function shout(string $string)
    {
        return strtoupper($string);
    }
}

Also Read : Laravel 9 OrderBy ASC and DESC Tutorial

Use it in your Blade template:

<!-- Code within resources/views/template.blade.php -->

{!! Helpers::shout('this is how to use autoloading correctly!!') !!}

Use this class anywhere in your Laravel app:

<?php // Code within app/Http/Controllers/SomeController.php

namespace App\Http\Controllers;

use Helper;

class SomeController extends Controller
{

    public function __construct()
    {
        Helpers::shout('now i\'m using my helper class in a controller!!');
    }
    ...

Thanks for reading the tutorial. Hope its help you for your coding! If you have any problem with this tutorial you can ask me in below comment section. Thank you.

Also Read : Rest API Authentication with Passport Laravel 9

5 Comments

Leave a Reply