How to create custom class or helpers in Laravel 5.*
For create a custom class or helpers or functions in laravel just follow below steps.
I Created Libraries directory under app directory . Where i will put my all custom classes or helpers functions.
Right now i create a Helpers Class under Libraries directory
app/Libraries/Helpers.php
Now I will create a new service provider for autoload all files under libraries directory.
hit below command in terminal or create a new class LibrariesProvider under app/Providers directory.
Now my app/Providers/LibrariesProvide.php is as below:
in register method i define that pick all .php files from Libraries directory and load it.
Now put App\Providers\LibrariesProvider::class into providers array in app.php under config directory
If you want to create alias of your custom class then follow below step.
Here i place my Helper alias for my Helpers class which located under Libraries directory. Put below line into aliases array in app.php under config directory.
Now do composer dump-autoload in terminal.
That's it.
I Created Libraries directory under app directory . Where i will put my all custom classes or helpers functions.
Right now i create a Helpers Class under Libraries directory
app/Libraries/Helpers.php
<?phpnamespace App\Libraries; class Helpers{ public static function test() { return "Test"; }}
?>
Now I will create a new service provider for autoload all files under libraries directory.
hit below command in terminal or create a new class LibrariesProvider under app/Providers directory.
php artisan make:provider LibrariesProvider
Now my app/Providers/LibrariesProvide.php is as below:
<?php namespace App\Providers; use Illuminate\Support\ServiceProvider; class LibrariesProvider extends ServiceProvider{ /** * Bootstrap the application services. * * @return void */ public function boot() { // } /** * Register the application services. * * @return void */ public function register() { foreach (glob(app_path().'/Libraries/*.php') as $filename){ require($filename); } }}
in register method i define that pick all .php files from Libraries directory and load it.
Now put App\Providers\LibrariesProvider::class into providers array in app.php under config directory
If you want to create alias of your custom class then follow below step.
Here i place my Helper alias for my Helpers class which located under Libraries directory. Put below line into aliases array in app.php under config directory.
'Helper' => App\Libraries\Helpers::class
Now do composer dump-autoload in terminal.
That's it.
I'm glad I was able to help
ReplyDelete