laravelcontrollerglobal

how to create global function that can be accessed from any controller and blade file


I have two controller file homecontroller and backendcontroller. What is the best way to create global function and access it from both files?

I found here Arian Acosta's answer helpful but I wonder if there is an easiest way. I would appreciate any suggestions.


Solution

  • Updated:

    Step 1 Add folder inside app folder app->Helper

    Step 2 add php Class inside Helper folder Eg. Helper.php

    Add namespace and class to the Helper.php

    namespace App\Helper;
    
    class Helper
    {
    
    }
    

    Register this Helper.php into config/app.php file

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

    Now, write all the functions inside Helper.php and it will be accessible everywhere.

    How to access from Controller?

    Step 1 - Add a namespace at top of the controller.

    use App\Helper\Helper;
    

    Step 2 - Call function - Assume there a getInformation() inside the Helper Class.

    $information = Helper::getInformation()