How to create a method able for use everywhere in Laravel

2.1k Views Asked by At

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.

2

There are 2 best solutions below

3
On BEST ANSWER

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();
0
On

create a function in a php file and add it in composer.json file inside "autoload" attribute, like this:

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

and run composer dump-autoload command, Here - CustomHelper.php is the file, i want to autoload and their function can be used anywhere in your project

CustomHelper.php

<?php

  if (! function_exists('getOTP')) {
    function getOTP()
    {
        return str_pad(rand(0, pow(10, 4) - 1), 4, '0', STR_PAD_LEFT);
    }
  }

 ?>

now you can call getOTP() function anywhere in your project