To use external classes or any other PHP library into your Laravel project, you have to do the following steps:
1. Create a folder somewhere in your Laravel app that will contain the PHP files you're going to use:
For example you have a custom class, create a folder in the directory app/libraries
. Inside app/libraries
, paste the PHP files you'll be using [the library files you've downloaded].
2. In your composer.json
file, add the
folder/directory into your autoload classmap:
"autoload": {
"classmap": [
"app/commands",
"app/controllers",
"app/models",
"app/libraries", 50, 'silver' => 100, 'gold' => 150];
}
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:
public function getHome[] { include[app_path[] . '\functions\prices.php']; $prices = getPrices[]; // ...
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]
"autoload": { "classmap": [ "database" ], "psr-4": { "App\": "app/" }, "files": [ "app/functions/prices.php" ] },
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":
"autoload": { "classmap": [ "database", "app/functions" ], },
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.