1cookie's avatar

Dependency injection for eloquent models

Is this possible in Laravel 9.0+?

<?php


class Car 
{
	public $engine;
	public $model;
	public $year;
	
	public function __construct($engine, $model, $year){
		$this->engine = $engine;
		$this->model = $model;
		$this->year = $year;
	}
	
	public function getEngine(){
		return $this->engine;
	}
	
	public function getModel(){
		return $this->model;
	}
	
	public function getYear(){
		return $this->year;
	}
	
	public function foo(){
		return 'foo';
	}
}

class Vehicle 
{
	public $type;
	
	public function __construct($type){
		$this->type = $type;
	}
}

class Rental 
{
	public $vehicle;
	
	public function __construct(Vehicle $vehicle){
		$this->vehicle = $vehicle;
	}
}
 
$rental = new Rental(new Vehicle(new Car(2.3, 'BMW', '2019')));

var_dump($rental);
object(Rental)#1 (1) {
  ["vehicle"]=>
  object(Vehicle)#2 (1) {
    ["type"]=>
    object(Car)#3 (3) {
      ["engine"]=>
      float(2.3)
      ["model"]=>
      string(3) "BMW"
      ["year"]=>
      string(4) "2019"
    }
  }
}


Database
+-------------------------------------+
Rental >
- id
- vehicle ['car', 'bike', 'boat',...]
- engine
- model
- year

thanks in advance

0 likes
3 replies
LaryAI's avatar
Level 58

Yes, it is possible to use dependency injection for Eloquent models in Laravel 9.0+. You can use the make method to inject the model into the constructor of the class. For example, you can inject the Car model into the Rental class like this:

class Rental 
{
	public $vehicle;
	
	public function __construct(Car $vehicle){
		$this->vehicle = $vehicle;
	}
}

$rental = app()->make(Rental::class);

Then you can access the properties of the Car model like this:

$rental->vehicle->getEngine();
$rental->vehicle->getModel();
$rental->vehicle->getYear();

You can also use the make method to inject the Car model into the Vehicle class like this:

class Vehicle 
{
	public $type;
	
	public function __construct(Car $type){
		$this->type = $type;
	}
}

$vehicle = app()->make(Vehicle::class);

Then you can access the properties of the Car model like this:

$vehicle->type->getEngine();
$vehicle->type->getModel();
$vehicle->type->getYear();

Hope this helps!

Snapey's avatar

I would not recommend you create public properties and get/setters if these are the same names as columns in your database.

Why not use the model as it is intended?

jlrdw's avatar

To add, I would also suggest the Free laravel training from right here.

Please or to participate in this conversation.