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

9

73

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.

Darlenadarlene answered 17/5, 2017 at 10:2 Comment(0)
T
69

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()
Torietorii answered 17/5, 2017 at 10:22 Comment(9)
Hi Rahul. This worked for me. I choose the answer as an accepted answer as I think this is the easiest way to do this.Darlenadarlene
where do you make the file? is it anywhere?Lore
@Rahul your answer is not complete. Please update it so that user can know what is path of common.php file. Thanks.Airiness
is there a way I can make that method to run automatically in the controller, without having to explicitly calling it?Monzonite
how do you acces helper function using an alias?Ingraham
how do I call a helper function from a controller?Selfexistent
add a namespace to the controller. Eg. if the class name is Helper. use App\Library\Helper; public function getData() { Helper::getInformation(); }Torietorii
How to use the helper function in Lumen 8.0? Please share your views. Thanks a lot.Airiness
How can i access in Blade file ?Trisomic
O
88

Easy Solution:

  1. Create a new Helpers folder under the app folder.

  2. Create a .php file named helper_functions.php in the Helpers folder.

  3. Add your PHP function(s) to helper_functions.php

    //Examples
    function function_a($params){       
        //add your code
    } 
    
    function function_b($params){        
        //add your code
    }
    
  4. Add helper_functions.php path to the Files section of composer.json:

    
    "autoload": {
        ...
        "files": [
            "app/Helpers/your_helper_function.php"
        ]
        ...
    }
    
  5. Refresh Composer autoload files. (Run this in your project directory)

    composer dump-autoload

That's it! you can access function_a() or function_b() in any part of your Laravel project.


I also have a blog post that covers the same topic:

How to Add a Global Function in Laravel Using Composer?

Ostrich answered 17/5, 2017 at 10:14 Comment(7)
Hi Sapnesh. what the command composer dump-autoload really does? Does it create new files?Darlenadarlene
@hijacker83 When your project is run the composer loads some files into memory, for seamless coding experience (no namespace hassle and all) so whenever you make any changes to the composer.json file (which composer uses to auto load dependencies) you should run composer dump-autoload which will dump currently loaded files and load according to the changed config file. It's just good practice to avoid problemsOstrich
Thanks for the method.Darlenadarlene
I think it's the best way to do thatGlycerite
If you are working with big team or you are planning for feature, it is not recommended way, because it can be a "magical" methods. Other developers can spend plenty time to understand how magic method comes in. For my opinion, the Helpers way are much more better (with config/app.php).Eckenrode
/!\ This method imply the file NOT TO BE NAMESPACED. Want to add this little warning since I was playing around with both (main) solutions explained here and ended up with a namespace in my autoloaded file.Gualterio
This is the simple way, I like it. For now I'm using app/Common.php which is the same Codeigniter 4 does.Meyerhof
H
85

Solution

One way to do this is to create a class and use its instance, this way you can not only access the object of the class within a controller, blade, or any other class as well.

AppHelper file

In you app folder create a folder named Helpers and within it create a file name AppHelper or any of your choice

<?php
namespace App\Helpers;

class AppHelper
{
      public function bladeHelper($someValue)
      {
             return "increment $someValue";
      }

     public function startQueryLog()
     {
           \DB::enableQueryLog();
     }

     public function showQueries()
     {
          dd(\DB::getQueryLog());
     }

     public static function instance()
     {
         return new AppHelper();
     }
}

Usage

In a controller

When in a controller you can call the various functions

public function index()
{
    //some code

   //need to debug query
   \App\Helpers\AppHelper::instance()->startQueryLog();

   //some code that executes queries
   \App\Helpers\AppHelper::instance()->showQueries();
}

In a blade file

Say you were in a blade file, here is how you can call the app blade helper function

some html code
{{ \App\Helpers\AppHelper::instance()->bladeHelper($value) }}
and then some html code

Reduce the overhead of namespace (Optional)

You can also reduce the overhead of call the complete function namespace \App\Helpers by creating alias for the AppHelper class in config\app.php

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

and in your controller or your blade file, you can directly call

\AppHelper::instance()->functioName();
Homovec answered 17/5, 2017 at 12:2 Comment(4)
hi! it seems very advanced for me. Do I need to use always use public static function instance() { return new AppHelper(); } then call any function with \App\Helpers\AppHelper::instance()->functionname(); ?Darlenadarlene
You can remove instance function and make all the other functions static functions and make direct call AppHelper::bladeHelper(). The instance function helps me to initialize things in constructor or chain function calls.Homovec
just me or do you need to do a composer dump-autoload for Laravel to recognize the new file?Ingraham
This proposal is inefficient because it creates a new instance of a class every time instance is called. Moreover, it seems that the "global" functions are completely unrelated to each other and don't use anything which requires a "this"-object. So there is absolutely no reason why they should be part of the same class. This seems to be a complete misuse of the concept of OOP and is simply bad coding style.Scorper
T
69

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()
Torietorii answered 17/5, 2017 at 10:22 Comment(9)
Hi Rahul. This worked for me. I choose the answer as an accepted answer as I think this is the easiest way to do this.Darlenadarlene
where do you make the file? is it anywhere?Lore
@Rahul your answer is not complete. Please update it so that user can know what is path of common.php file. Thanks.Airiness
is there a way I can make that method to run automatically in the controller, without having to explicitly calling it?Monzonite
how do you acces helper function using an alias?Ingraham
how do I call a helper function from a controller?Selfexistent
add a namespace to the controller. Eg. if the class name is Helper. use App\Library\Helper; public function getData() { Helper::getInformation(); }Torietorii
How to use the helper function in Lumen 8.0? Please share your views. Thanks a lot.Airiness
How can i access in Blade file ?Trisomic
W
18

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://mcmap.net/q/271878/-how-to-create-global-function-that-can-be-accessed-from-any-controller-and-blade-file and https://mcmap.net/q/271878/-how-to-create-global-function-that-can-be-accessed-from-any-controller-and-blade-file

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();
    
Wen answered 6/8, 2020 at 16:15 Comment(0)
T
10

In your Controller.php which extends BaseController, you can create a function like;

public function data($arr = false)
{
 $data['foo'] = 'bar';
 return array_merge($data,$arr);
}

And from any controller when you send a data to a view;

public function example()
{
 $data['smthg'] = 'smthgelse';
 return view('myView',$this->data($data));
}

The data in the the main controller can be accessed from all controllers and blades.

Thesda answered 17/5, 2017 at 11:40 Comment(2)
I use that solution, but the function doesn't work in __construct function. But, I think it's a simple and clear way to do that.Moscow
It is a bad practice to define functions that are unrelated to standard MVC operations inside controller. Would be wise to put them in a service.Liu
C
4

Laravel uses namespaces by default. So you need to follow the method described in that answer to setup a helper file.

Though in your case you want to access a method in different controllers. For this there's a simpler way. Add a method to you base controller app/Http/Controllers/Controller.php and you can access them in every other controller since they extend it.

// in app/Http/Controllers/Controller.php
protected function dummy()
{
    return 'dummy';
}

// in homecontroller

$this->dummy();
Caryloncaryn answered 17/5, 2017 at 10:12 Comment(0)
L
2

There are a few ways, depending on the exact functionality you're trying to add.

1) Create a function inside Controller.php, and make all other controller extend that controller. You could somewhat compair this to the master.blade.php

2) Create a trait, a trait can do a lot for you, and keeping ur controllers clean. I personally love to use traits as it will look clean, keep my Controller.php from being a mess with tons of different lines of code.

Lomeli answered 17/5, 2017 at 10:16 Comment(2)
first time I heard about the trait. I found useful article here conetix.com.au/blog/simple-guide-using-traits-laravel-5 thank you very much.Darlenadarlene
@hijacker83 You are welcome, I would recommend having a good look into this, it will keep your code much cleaner than making 1 file having a ton of different functions that will become a mess.Lomeli
P
0

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

Preclude answered 27/4, 2021 at 14:41 Comment(0)
A
0

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

Antacid answered 31/8, 2022 at 7:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.