Hamed Kamrava
Hamed Kamrava

Reputation: 12847

How can I add external class in Laravel 5

There is a class in app/Libraries/TestClass.php with following content:

class TestClass {
      public function getInfo() {
           return 'test';
      }
}

Now, I would like to call getInfo() method from this external class in my Controller.

How can I do such thing?

Upvotes: 13

Views: 14721

Answers (1)

lukasgeiter
lukasgeiter

Reputation: 152870

First you should make sure that this class is in the right namespace. The correct namespace here would be:

namespace App\Libraries;

class TestClass {

Then you can just use it like any other class:

$test = new TestClass();
echo $test->getInfo();

Don't forget the import at the top of the class you want to use it in:

use App\Libraries\TestClass;

In case you don't have control over the namespace or don't want to change it, add an entry to classmap in your composer.json:

"autoload": {
    "classmap": [
        "app/Libraries"
    ]
}

Then run composer dump-autoload. After that you'll be able to use it the same way as above except with a different (or no) namespace.

Upvotes: 26

Related Questions