Search code examples
phplaravellaravel-5laravel-5.8laravel-helper

How to create a method able for use everywhere in Laravel


I want to make some changes to dates, for example, I want to explode it do some operation and implode it again, and I want to use it all around my app so here is my code :

$divided_date = explode('/', $request->point_date);
$converted_date = Verta::getGregorian($divided_date[0], $divided_date[1], $divided_date[2]); // [2015,12,25]
$begindate = implode('/', $converted_date);

I want to make a function called DateConvertor() for example, and anywhere that I want to convert the date I use something like below.

$request->somedate()->DateConvertor();

or for example

Dateconvertor($request->someday);

And it returns the converted date so now I don't know to use the static method or no, and I don't know where to define it so I can use it in all of my app not just a single model.


Solution

  • You can create a Helper.php file and in composer.json include that file as

    "files": [
            "app/Helpers/Helper.php",   
    ]
    

    or may add a helper class like

    <?php
    
    
    namespace App\Helpers;
    
    
    class Helper
    {
        public static function foo()
        {
            return 'foo';
        }
    }
    

    and config/app.php

    'aliases' => [
    
        ....
    
        'Helper' => App\Helpers\Helper::class,
    
    ]
    

    and then use as Helper::foo();

    or add a service provider like

    php artisan make:provider HelperServiceProvider 
    

    in register method

    public function register()
    {
        require_once app_path() . '/Helpers/Custom/Helper.php';
    }
    

    In config/app.php

    providers = [ 'CustomHelper' => App\Helpers\Custom\Helper::class, ]

    and

    'aliases' => [
    'CustomHelper' => App\Helpers\Custom\User::class,
    ]
    

    then use as

    CustomHelper::foo();