How to add custom class helper in laravel

In this tutorial i will show you how to create custom component helper class in laravel 5 framework. Here i'm creating CommonHelper.php class in directory app/Lib directory.

Laravel 5 Custom Class Component


Step 1: Here is your code for CommonHelper.php file.



<?php
namespace App\Lib;
 
class CommonHelper {
 
   public function getDate() {
        return date('Y-m-d H:i:s');
    }
}

Step 2: Now you can add the namespace(use App\Lib\CommonHelper) of commonHelper class in your controller file where you would like to use it.


<?php
 
namespace App\Http\Controllers;
 
use App\Lib\CommonHelper;
 
class TestController extends Controller {
 
   protected $commonHelper;
 
   public function __construct(CommonHelper $commonHelper) {
       $this->commonHelper = $commonHelper;
   }
 
  public function index() {
     print_r($this->getDate());
  }
 
}

getDate in commonHelper is non static method.static method will be accessed using  :: (scope operator).If getDate function is static then you call it like commonHelper::getDate(). I hope you understand how to create custom class in laravel . if you find any help related to this please comment.


No comments:

Post a Comment

Download the eBook of react js for beginners

ReactJS basically is an open-source JavaScript library which is used for building user interfaces specifically for single page applications...

Popular