In this chapter we will be learning how to auto-load files in laravel which will be loaded automatically when our application runs in this Auto-loading in Laravel tutorial.
Auto-Loading allows you to load class files when they are needed without explicitly loading or including them. This gives you ease in running your application by loading those files automatically which are needed every time.
- Laravel is built to work with Composer. All the class auto-loading is handled by the Standard Composer autoloader.
- The files to be auto loaded are to be specified in the composer.json file.
- Laravel is setup to use class mapping by default for the following resource folders as shown below:
- Each time we run the composer dump-autoload, it cycles through these directories and creates a map of class names to file locations, so that it can load them later when needed. So when we create a new controller, we need to dump autoload it, to add it to the map.
- Instead of this we can use a namespaced structure to store all our files and dump autoload just once. Since composer knows that a namespace map up to a directory structure, it can guess where the file is supposed to be, so there is no need for a map.
- So let us create a folder/directory named sourceFiles in the app folder of the laravel folder which is in htdocs folder of xampp folder. All our application files will be contained in this folder.
- Now let us write a controller which will be placed inside the Controller folder which is created in sourceFiles folder.
- This above firstcontroller.php controller file is included in namespace sourceFiles\Controller. View is outside this namespace, i.e. in the root namespace, hence it is imported in it using the using keyword.
- To route this controller just add the following route to routes.php file:
- Now we can just specify our folder that contains all our application files in the composer and autoload them automatically just through it as shown below:
- This will autoload all the files of our application.
- Thus we learned that instead of specifying all the files that are to be auto loaded one by one in composer.json file, we can create a separate folder in the app folder of laravel and use a namespaced structure, so that by loading just the source folder we can autoload the application. The composer will understand as to which file is inside which namespace through the namespace structure.
class FirstController extends Controller
public function sayhello()
Thus we learned auto loading in this Auto-loading in Laravel tutorial.