ReFactoring Helper Functions to Static Class Methods In Laravel

Hello Artisan 

In this tutorial i am going to show you how we can create custom helper function in laravel using laravel facades. If you don't know how to use facades keyword in laravel get a static interface in your custom class, then you are a right place.

In this tutorial i will show you step by step that how we can use facades to get static proxies to a class. Simply we will create a folder in our app directory and then we will create our custom class. Using facades we will access our custom class from any where in our application.

We can create custom helper function in laravel in many way. But in this tutorial i will show you how we can create custom helper function in laravel and how we can access it using facades keyword.

 

how-to-use-laravel-facades

Step 1 : Create Helper Class

In this step first we have to create our custom helper class. So create it like following directory

app/Helper/Helper.php

namespace App\Helper;


class Helper {

   public function my_helper_function()
   {
       dd("Hello");
   }

}

 

Step 2 : Print Helper Class Data

In this step we have to access this helper class method. How we can access it in our controler? If this method is static method then we can access it like below condition

Helper::my_helper_function();

 

Read also : How to Create and Use Custom Facade in Laravel 6

 

But here our method is not static. So if you access it right now like below, it will show you this error.

routes/web.php

use App\Helper\Helper;

Route::get('/', function () {

    $data = Helper::my_helper_function();

});

As my_helper_function is not a static method that's why it is showing that we can not access it statically.

laravel-facades-vs-helper-function

 

But we can get this static interface in our class after adding just facades word before namespace. Just have a look

use Facades\App\Helper\Helper;

Look here, our file normally namespace is 

use App\Helper\Helper;

But here we add Facades before App. For adding it we have got static interface in our class. So now without making static method we can access as like a static method.

routes/web.php

use Facades\App\Helper\Helper;

Route::get('/', function () {

    $data = Helper::my_helper_function();

});

Now you can see the output of our custom helper function 

how-to-use-helper-function-in-laravel

Now there we go. So hope you have understood this mechanism that how we can create our custom helper class and how we can access it statically using facades.