Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 509
Johnny Avatar asked May 17 '17 10:05

Johnny


People also ask

How do you declare a global function?

Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function. To create a global variable inside a function, you can use the global keyword.


1 Answers

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(); 
like image 146
Max Gaurav Avatar answered Dec 09 '22 06:12

Max Gaurav