DEV Community

Cover image for How to use classes in Laravel
Snehal Rajeev Moon
Snehal Rajeev Moon

Posted on

How to use classes in Laravel

Hello friends!
In this blog post I am going to illustrate how and why we use classes in laravel.

Why we use it?
When the method is commonly used in one or more controller instead of writing the same code again and again we can create a class and reuse the code where we need it.
It helps us to remove the pain of writing the same code by easing common task.

How to use it?

  • Create a class file in App folder or we can create a file in App\Providers folder (the App\Providers folder is provided by laravel to create external file).

  • Now open the file and add namespace which is necessary.

namespace App\Providers
Enter fullscreen mode Exit fullscreen mode

if you do not see the Provider folder you can create one.

Let see an example

Create a PackageClass in App\Providers\PricePackage, open a file and add namespace in it.

namespace App\Providers\PricePackage
Enter fullscreen mode Exit fullscreen mode

now add below code in it

class PackageClass {
   public function getPackage() {
       return [
          'bronze' => 5000,
          'silver' => 10,000,
          'gold' => 20,000,
       ];
    }
}
Enter fullscreen mode Exit fullscreen mode

Now whenever we need the pricing we can call this class and use its methods, for that we need to instantiate the class object.
Open a controller file where you need to use it.
I am using it in PriceController and add the below code.

 public function index() {
   $objPricePackage = new PackageClass();
   $packages = $objPricePackage->getPackage();
   return view('packages.index', ['packages', $packages]);
 }
Enter fullscreen mode Exit fullscreen mode

In this way we can use external classes in laravel.

Thank you for reading 🦁 🦄

Latest comments (0)