How to use external classes and PHP files in Laravel Controller?

Laravel is an MVC framework with its own folder structure, but sometimes we want to use something external which doesn’t follow the same structure. Let’s review two different scenarios – when we have external class and when it’s just a .php file.

Let’s say we have a simple example, a PagesController.php file like this:

Pretty simple, right? Now, let’s say we want to have our product prices on the homepage, but they come from some kind of external class or PHP file.

Use an external class in Controller

Let’s say we have a simple class to define the prices:

Now, where to put this class and how to use it? A couple of steps here:

1. You can put a class itself anywhere you want within \App folder

By default, Laravel offers you some folders there like Providers, but I personally prefer to create a separate one – like App\Libraries, App\Classes or App\Services. Or you can call it your own application – App\MyApp. This is totally your choice.

So, in this example, let’s save the class as App\Classes\PricesClass.php.

2. Namespace within the file

Now we have to tell Laravel what is the namespace of this new file – it’s the same as the folder:

3. Use the class in your Controller

Let’s get back to our PagesController.php – here we have to add use statement for that external class, and then we’re free to use it! Like this:

That’s it, nothing more complicated than that.

Have you tried our tool to generate Laravel adminpanel without a line of code?
Go to QuickAdminPanel.com

Use an external PHP file in Controller

Another case – it’s not always an OOP file that we want to use. For some cases it’s just a list of functions. Of course, we can wrap them in a class as well, but not always. So, how to use the same function, if we just have a prices.php file like this:

And that’s it – no class, no namespace, nothing.
Let’s place our function as app/functions/prices.php file. Then – we have three different ways of include it:

1. Just include the class with PHP functions like include() or require() – and don’t forget app_path() function:

Note that you still need a slash symbol before the folder functions.
You can read more about app_path() and other Helper functions in the official documentation.

2. In composer.json file you just add needed files in “autoload” section – in a new entry called “files”:
(thanks for this suggestion to the commenters Joseph and Hisham)

This way you don’t need to use any include() functions anywhere within your controllers – just use the functions straight away.

3. Autoload the whole folder in composer.json
(thanks to YOzaz for pointing this out in comments)

Another way is just autoload the folder with that file – so you would place any similar external “helpers” in that folder, and that would be included in the future. In this case – add this folder in array or “classmap”:

Choose this option if you want those files to be included in a manner of “set it and forget it”.

Notice: if you make these changes to composer.json file, don’t forget to run composer dump-autoload for changes to take effect.

Liked the article? Maybe you need help with your Laravel project?
Check out my Upwork profile and hire me!

23 thoughts on “How to use external classes and PHP files in Laravel Controller?

  1. Nice post. In my opinion composer autoloading is better than file inclusion in controllers. File inclusion with “require” can be used when included file returns some values, like config files in Laravel.

  2. Povilas, it’s better to use class autoload instead of files autoload in composer – more flexible.

    “classmap”: [
    “app/functions/my”
    ]

    Then all custom files can be placed in “my” folder and will be loaded automaticaly. No need to specify additional files when they are created by modifying composer.json.

    1. Hi, I’m new to laravel. Can someone clarify this….If I used YOzaz’s suggestion to use class autoload, then does that mean I wouldn’t have to use “use App\Classes\PricesClass;” in my controller at all? And, how does the controller know where to look for the class? And doesn’t it slow the execution of the code if you have many folders to autoload, because the controller has to look for the right class in all those folders?

      Also, let’s say you have 2 different php SDKs that you want to include in your project, for example FB and Twitter. What if they both had the same class names (I know they don’t, but if you use some less known applications they could be using generic names for their classes. For example instead of FacebookClass, it could be CustomClass), and you placed both of them in the autoload, then how would the controller know which one you are trying to call if they have the same name but are located in different folders?

      Also, let’s say I created a folder in App\ directory called Services, then I put different SDKs inside of it (e.g: FB, Twitter, etc…). If I use class autoload in composer do I only list the top directory like this:

      “classmap”: [
      “app/services”
      ]

      or do I have to list every folder inside the services folder, like this:

      “classmap”: [
      “app/services/fb”,
      “app/services/twitter”,
      ]

      If it is the first one (“app/services”), then how does the controller know where to look for the class?

      thanks

    2. This doesn’t work for functions. Although this comment is 2 years late but better late than never.
      “classmap” only autoloads classes. If your function is offered as method of a class it is fine but a standalone function won’t autoload. This is confirmed in the official documentation of composer: https://getcomposer.org/doc/04-schema.md#classmap

      What I do is autoload a php file in functions folder using “files” key of composer. The file contains
      require_once(‘functionOne.php’); require_once(‘functionTwo.php’); …. so on.

      1. Hi Tuhin, just want to say thanks. I come across this problem some time ago, so I’m a bit confused to see the classmap suggestion. Little did I know it was because I’m using standalone functions instead of classes.

        Thanks again for the knowledge.

  3. Greate article; however, I think it is more laravel-way to use DI for adding various classes in controller.

    For instance, if you want to inject object just use class constructor with class-hinting.
    class PagesController extends Controller {
    private $pricesClass;
    public function __constructor(\App\Classes\PricesClass $pricesClass) {
    $this->pricesClass = $pricesClass;
    }
    }

    Another way is to access class through laravel container:
    class PagesController extends Controller {
    public function getHome() {
    $pricesClass = app(‘\App\Classes\PricesClass’);
    $prices = $pricesClass->getPrices();
    return view(‘pages.home’, compact(‘prices’));
    }
    }

  4. Would you know why after adding my external file to composer.json and dump autoload, I am able to access functions defined in the added file without a problem, but I am getting a Call to a member function make() on null …helpers.php line 62 ?

    The helpers line suggests that the function app make is not able to get an instance of my file…does this make sense since I am able to call and use a function within my external file?

    Any pointers? Anyone?

  5. i want to use mage.php from magento in laravel i follow those steps but i always have the same error “include_once(Mage/Core/functions.php): failed to open stream: No such file or directory” how can i resolve this please

  6. Hello, thanks for the nice article. I found one problem when make a helper class file and use it as autoload. How can I confirm a class file is accessible from both Controller and View files, if I autoload a file. Any guide will be appreciable.

  7. Method 1 Use an old-style external PHP file in Controller is cool.
    No hassle in using non-namespace classes.

    I used this to use my class in laravel.
    include(app_path() . ‘\Libs\myclass.php’);
    $obj = new \myClass();

    If you think to migrate to latest laravel, things are very much over-complicated.

  8. I’m a little late to the party, but this article is just the thing I needed. I’d prefer to use Laravel’s auto-include voodoo, but I like to know the whole story in case I ever do want to do a manual include such as this. Sometimes being a little more explicit for a minor inconvenience can be a good thing for more readable code.

  9. Hello my friend, first of all I want to congratulate you for your excellent article, it helped me a lot, I have a big doubt,

    If I add my classes in a folder called Libraries, and I put the classes in the composer.json file, in classmap the class folder, are all these classes loaded on all the pages I use?
    Or are they only loaded when they are used?
    I ask for optimization of the application.

  10. Thanks, the first solution works perfectly. I don’t need to autoload as it is only useful in one method and in one controller. God bless you for helping out the community.

Leave a Reply

Your email address will not be published. Required fields are marked *