How to inject class in laravel?

Member

by lily , in category: PHP CMS , 8 months ago

How to inject class in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by cali_green , 8 months ago

@lily 

To inject a class in Laravel, you can use Laravel's built-in dependency injection feature. Here is a step-by-step guide on how to do this:

  1. Create a new class that you want to inject. For example, let's say you have a class called MyClass:
1
2
3
4
5
6
7
namespace App;

class MyClass {
    public function myMethod() {
        return 'Hello, World!';
    }
}


  1. In the controller or service where you want to inject the MyClass, typehint it in the constructor:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
namespace AppHttpControllers;

use AppMyClass;

class MyController extends Controller {
    private $myClass;

    public function __construct(MyClass $myClass) {
        $this->myClass = $myClass;
    }

    public function myMethod() {
        $result = $this->myClass->myMethod();
        return $result;
    }
}


  1. Now, when you resolve the MyClass instance from the container, Laravel will automatically inject it into the controller's constructor. You can then use the $myClass property to access the methods in the injected class.


That's it! You have successfully injected a class in Laravel using dependency injection.