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

Viewed 71941

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.

9 Answers

The Laravel Service Provider way

I've been using global function within Laravel for a while and I want to share how I do it. It's kind of a mix between 2 answers in this post : https://stackoverflow.com/a/44021966/5543999 and https://stackoverflow.com/a/44024328/5543999

This way will load a file within a ServiceProvider and register it within your Laravel app.

Where is the difference, the scope, it's always about the scope.

Composer //Autload whitin composer.json method
|
|--->Laravel App //My method
     |
     |--->Controller //Trait method
     |--->Blade //Trait method
     |--->Listener //Trait method
     |--->...

This is a really simplist way to explain my point, all three methods will achieve the purpose of the "Global function". The Traits method will need you to declare use App\Helpers\Trait; or App\Helpers\Trait::function().

The composer and service provider are almost about the same. For me, they answer better to the question of what is a global function, because they don't require to declare them on each place you want to use them. You just use them function(). The main difference is how you prefer things.

How to

  1. Create the functions file : App\Functions\GlobalFunctions.php

    //App\Functions\GlobalFunctions.php
    <?php
    
        function first_function()
        {
            //function logic
        }
    
        function second_function()
        {
            //function logic
        }
    
  2. Create a ServiceProvider:

     //Into the console
     php artisan make:provider GlobalFunctionsServiceProvider
    
  3. Open the new file App\Providers\GlobalFunctionsServiceProvider.php and edit the register method

     //App\Providers\GlobalFunctionsServiceProvider.php
    
     public function register()
     {
         require_once base_path().'/app/Functions/GlobalFunctions.php';
     }
    
  4. Register your provider into App\Config\App.php wihtin the providers

     //App\Config\App.php
    
     'providers' => [
    
         /*
         * Laravel Framework Service Providers...
         */
         Illuminate\Auth\AuthServiceProvider::class,
         ...
         Illuminate\Validation\ValidationServiceProvider::class,
         Illuminate\View\ViewServiceProvider::class,
         App\Providers\GlobalFunctionsServiceProvider::class, //Add your service provider
    
  5. Run some artisan's commands

     //Into the console
     php artisan clear-compiled
     php artisan config:cache
    
  6. Use your new global functions

     //Use your function anywhere within your Laravel app
     first_function();
     second_function();
    

Creating a global function

create a Helpers.php file under a folder, let's name it 'core'.

core
 |
  -- Helpers.php


namespace Helpers; // define Helper scope

if(!function_exists('html')) {

  function html($string) {

    // run some code
    
    return $str;

  }

}

In your composer.json

"autoload": {
    "psr-4": {
        
    },
    "files": [
        "core/Helpers.php"
    ]
}

in the file that you want to use it

// the " use " statement is not needed, core/Helpers is loaded on every page

  if(condition_is_true) {

   echo Helpers\html($string);die(); 

  }

Remove the namespace in Helpers.php if you want to call your function without the need to prefix namespace. However I advise to leave it there.

Credit: https://dev.to/kingsconsult/how-to-create-laravel-8-helpers-function-global-function-d8n

By using composer.json and put the function containing file(globalhelper.php) to the autoload > files section, then run

composer dump-autoload

You can access the function inside the file(globalhelper.php) without having to calling the class name, just like using default php function.

composer.json 's autoload section

Related