Custome helper class in laravel
Comment (0)
Admin
Creating a custom helper class in Laravel involves creating a class with static methods that encapsulate the desired functionality. Here's a step-by-step guide:
1. Create a Helper Class:
Create a new PHP class in your Laravel application, for example, in the app/Helpers
directory. You can name it something like CustomHelper.php
.
// app/Helpers/CustomHelper.php
namespace App\Helpers;
class CustomHelper
{
public static function customFunction()
{
return 'Custom function executed!';
}
public static function anotherFunction($parameter)
{
return 'Received parameter: ' . $parameter;
}
}
2. Register the Helper Class:
Laravel autoloads classes following the PSR-4 namespace convention. To autoload your custom helper class, add its namespace to the composer.json
file in the
autoload
section:
"autoload": {
"classmap": [
// ...
],
"psr-4": {
"App\\": "app/",
"App\\Helpers\\": "app/Helpers/"
}
},
After modifying composer.json
, run the following command to autoload the new class:
composer dump-autoload
3. Use the Helper Class:
You can now use your custom helper class anywhere in your Laravel application. For example, in a controller or another class:
// In a controller or another class
use App\Helpers\CustomHelper;
class YourController extends Controller
{
public function yourMethod()
{
$result = CustomHelper::customFunction();
// Use $result...
}
}
Make sure to import the helper class at the top of the file where you want to use it.
That's it! You've created a custom helper class in Laravel. This approach helps keep your code organized and makes it easy to reuse common functionality throughout your application.
Hope it will help you.....
Thanks!
Comments (0)
Your Comment