We can easily import Laravel classes anywhere in the application. It is equally easy to do if you are thinking of creating your own classes and functions in Laravel. One of the reasons we may want to create our own classes is to have customized functionality in our Laravel app. Though we can write code in the controllers, it’s recommended to extract extra functionality from controllers to other classes or functions. This way, we can keep controllers clean and more focused on the main task. Classes can also be used to reuse the code over and over again in your application. For example, I create custom classes to generate user notifications and initiate the notification class wherever I want.

Create Classes & functions in Laravel

It is better to create custom classes in a separate directory. Create a directory inside the app directory. For the illustration, I am going to create a Classes directory in the app. +– app| +– Classes To create a class that generates users’ notifications, let’s create Notification.php class inside the Classes directory. +– app| +– Classes| +– Notification.php