Spread the love

Laravel provides various packages and library to enhance our application features and functionalities but sometime we want our own class to handle the few features of the application. Thus I this article i will show you to create a class and use it using the alias or directly from the namespace name.

Let’s begin the tutorial of custom helper functions step by step

Step 1 : Create a class file

First step is create a helper file in app folder or we can create a folder named as Lib in app folder then we can create multiple files in that folder. in this example i am going to create a file in app/Lib/PaymentHelper.php

<?php 
namespace \App\Lib;

class PaymentHelper{

public $key='test_key';

  function getConfig(){
    return $this->key;
  }

}

Step 2 : Create Routes

Now, Create a route to check our implementation on controller or route itself using anonymous function.

<?php

use Illuminate\Support\Facades\Route;
 
Route::get('/helper',function(){
   
   $Payment=new \App\Lib\PaymentHelper();
    return $Payment->getConfig();
}); 

Or in controller

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ArticleController;

 
Route::get('/helper',[ArticleController::class, 'test']); 

Create a controller in app\Http\Controllers\ArticleController and method helper

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
user App\Lib\PaymentHelper;

class ArticleController extends Controller
{
    public function test(Request $request)
    {
        $Payment=new PaymentHelper();
        return $Payment->getConfig();
    }
}
?>

In the same way we can use it in our view file.

Leave a Reply