Call to a Member Function cadastrarDados() on null - Laravel

Asked

Viewed 467 times

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?

  • Your problem is in the DI itself that is not inserting the dependency.

  • @Marcosdacruzsibiliojr. I forgot to mention the error message: Call to a Member Function register.

  • @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.

  • @Helderferrari probably your model doesn’t have the method $this->central->cadastrarDados, post your model or repositório so we can help you better.

  • @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.

Show 1 more comment
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.