3
Good morning to all,
I am developing an application in Laravel 5.6 using PHP 7.2, I am having problems using DI(dependency Injection) in the constructor, since when creating the object manually the algorithm works perfectly, follows example:
THIS ONE DOESN’T WORK:
Centralcontroller
<?php
namespace App\Http\Controllers;
use App\Models\Central;
class CentralController extends BaseController
{
protected $central;
public function __construct(Central $central)
{
$this->central = $central;
}
public function centralParser(Request $request)
{
$this->central->cadastrarDados($request->all());
...
}
Basecontroller
namespace App\Http\Controllers;
use App\Models\Usuario;
class BaseController extends ResponseController
{
protected $usuario;
public function __construct(Usuario $usuario)
{
$this->usuario = $usuario;
}
//metodos......
}
This Works:
Centralcontroller
<?php
namespace App\Http\Controllers;
use App\Models\Central;
class CentralController extends BaseController
{
public function centralParser(Request $request)
{
$central = new Central();
$central->cadastrarDados($request->all());
...
}
}
Basecontroller
namespace App\Http\Controllers;
use App\Models\Usuario;
class BaseController extends ResponseController
{
protected $usuario;
public function __construct(Usuario $usuario)
{
$this->usuario = $usuario;
}
//metodos......
}
What is the error message?
– Marcos da Cruz Sibilio Jr.
Your problem is in the DI itself that is not inserting the dependency.
– Gabriel Heming
@Marcosdacruzsibiliojr. I forgot to mention the error message: Call to a Member Function register.
– Helder Ferrari
@Gabrielheming , exactly, creating the object manually I can call the method, now through the DI did not work. I would like to understand to avoid possible future mistakes in this project.
– Helder Ferrari
@Helderferrari probably your model doesn’t have the method
$this->central->cadastrarDados
, post yourmodel
orrepositório
so we can help you better.– William
@William the model has the registration method(). Debugging the code, I realized that the fault is in the constructor, because it does not bring me the object, so I can not make the call to the model.
– Helder Ferrari