Online Snippets Library

Create helper class In Laravel

In laravel we can create our own helper class to avoid repeating code.Helper class is simply a collection of functions in a particular category.

We will use following step to creare our own helper class.

Step 1

Create library folder inside app directory.

Step 2

Create a new file inside app/library/dateHelper.php and add follwing code.

<?php
class dateHelper
{
   public static function dateFormate($date)
    {
   // change dateformate
  return date('m M Y', strtotime($date));
    }
   
   public static function date_now()
      {
   // returns current time/date
    return date('Y-m-d H:i:s');
     }
  }
Step 3

Open composer.json file and add below lines to the classmap section.

"app/library", "app/library/dateHelper.php", Step 4

Now we will create route.

Route: Route::resource('helperdemo','HelperDemoController'); Step 5

Create Controller file inside app/controllers/HelperDemoController.php.

<?php

class HelperDemoController extends BaseController {
  public function index()
  {
$dateOld=dateHelper::date_now();
echo $datenew = dateHelper::dateFormate($dateOld);
  }
}
Step 6

Run "composer dump-autoload".


remove-index.php-from-url-in-codeigniter