Mohamed Nagy
Mohamed Nagy

Reputation: 1058

How to use external php classes in laravel framework?

I'm switching from Codeigniter to Laravel. In CI its easy to user external libraries or classes, just put it in application/libraries folder then load it from your controller by:

$this->load->library('libraryName')

Now, I wanna do the same thing in Laravel. I used this scenario :

  1. Create a folder inside my app folder called libraries.
  2. Change the composer.json (which located in the root) as the following:

    "autoload": {
      "classmap": [
        "app/commands",
        "app/controllers",
        "app/models",
        "app/database/migrations",
        "app/database/seeds",
        "app/tests/TestCase.php",
        "app/libraries" // this was added
      ]
    },
    
  3. And from CMD run the command composer dump-autoload.

My class look like this:

class Messages{
    function errorMessage(){//....}
    function successMessage(){//....}
}

Class stored in file called Messages.php which located in app\libraries folder.

I still have the same error:

Class 'Messages' not found

What is the problem and what is the solution?

Upvotes: 1

Views: 3674

Answers (2)

Vasiliy Bondarenko
Vasiliy Bondarenko

Reputation: 341

check your file with autoloading classes /vendor/composer/autoload_classmap.php your class should in there. if it is - check do you actually using composer autoloading on your request?

Upvotes: 0

Hans Ott
Hans Ott

Reputation: 609

  1. Create a new folder: app/your-folder-name and put your class in that folder
  2. Open the globals.php file in app/start
  3. You should see this:

    ClassLoader::addDirectories(array(
    
      app_path().'/commands',
      app_path().'/controllers',
      app_path().'/models',
      app_path().'/database/seeds',
    
    ));
    
  4. Add your folder with your class to this array

    app_path().'/your-folder-name'
    

More info can be found here: Where do I put Laravel 4 helper functions that can display flash messages?

Upvotes: 4

Related Questions