DEV Community

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

Posted on

6

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 🦁 πŸ¦„

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free β†’