In Laravel, you can create custom classes or custom library in laravel that can be used throughout your application. These classes can be used to encapsulate common functionality, business logic, or to abstract away complex operations. 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 You can now use your custom class in your application by importing it and creating a new instance of it. For example, in a controller:
<?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.
Pro Tips:
If you want to make your custom class or library class globally available throughout your application, you can register it in the AppServiceProvider class. For example:
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\MyCustomClass;
class AppServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->singleton('myCustomClass', function () {
return new MyCustomClass();
});
}
}
You can now use your custom class or library class anywhere in your application by calling the global helper function app()
and passing in the name of the class you registered. For example:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class MyController extends Controller
{
public function index(Request $request)
{
$customClass = app('myCustomClass');
// Use your custom class here
$customClass->myCustomFunction();
}
}
That’s it! You now know how to create custom classes or library classes in Laravel.