Posted by Arjun on Sunday 14th February 2016

How to add custom class in Laravel 5

How to Laravel 5 Laravel 5.x

In this tutorial, I will show you how to add a custom PHP class in Laravel 5.x application. For example, Lets call our class Common.php. Create a directory called Mylibs in app directory along with your class, Ex: Common.php. Make sure to add the correct namespace to the class as for your directory structure, in this example it is App\Mylibs as our common.php file located at App\Mylibs\Common.php

How to add custom class in Laravel 5

Example Custom class in Laravel 5

Here is my final class :

namespace App\Mylibs;
 
class Common {
 
   public function getName() {
        return 'Arjun';
    }

    public static function getLastName() {
        return 'PHP';
    }
 
}

Now, you can access this class using the namespace within your classes just like other Laravel classes.
use App\Mylibs\Common

<?php

namespace App\Http\Controllers;

use App\Mylibs\Common;

class AccountController extends Controller {

   protected $common;

   public function __construct(Common $common) {
       $this->common = $common;
   }

  public function index() {
     dd($this->common->getName());
  }

  public function getLastName() {
     dd(Common::getName());
  }

}

That is it.