Laravel create helper which can be accessed anywhere
Many times we need some general functions which needs to be called from many controllers or blades. So creating same function in multiple files is not feasible solution. So let me tell you how you can create helper file which will be loaded in every controllers, models and blades.
First we need to create new service provider by following command,
php artisan make:provider HelperServiceProvider
Now register this helper in config/app.php
'providers' => [
// Other Service Providers
App\Providers\HelperServiceProvider::class,
],
Now it’s time to use this provider. Go to app/Providers and edit HelperServiceProvider.php and add below code
app/Providers/HelperServiceProvider.php
<?phpnamespace App\Providers;use Hamcrest\Util;
use Illuminate\Support\ServiceProvider;class HelperServiceProvider extends ServiceProvider
{protected $helpers = [
'Helper',
'Constants',
]; /**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
//
} /**
* Register the application services.
*
* @return void
*/
public function register()
{
foreach ($this->helpers as $helper) {
$helper_path = app_path().'/Helpers/'.$helper.'.php'; if (\File::isFile($helper_path)) {
require_once $helper_path;
}
}
}
}
Let me tell you what we have done here. First I have created new array $helpers and added helper file names which I will create in next step. Then in register function I have loop this array and required these files by app_path().’/Helpers/’.$helper.’.php’ line. It means it will required “app/Helpers/Helper.php” and “app/Helpers/Constants.php”.
So let’s create our helper files now.
app/Helpers/Helper.php
<?php
use Carbon\Carbon;function formatDate($date){
return date("d/m/Y", strtotime($date));
}
app/Helpers/Constants.php
<?phpconst ACTIVE = 1;
const INACTIVE = 2;
So we have successfully created our helper files and it’s time to use this helpers.
In controller
public function index(Request $request){
$var = Model::where('status',ACTIVE)->get();
}
In blade
{{ formatDate($var['created_at']) }}