Search code examples
phplaravellumenphp-7.2

Injecting object into controller throw an error


I have a project in laravel with a model called Teacher.

I have model file , controller with this code.

/**
  * @param Teacher $Teacher
  * @return \App\Http\Resources\Teacher
  */
public function show(Teacher $Teacher) : \App\Http\Resources\Teacher
{
    return new \App\Http\Resources\Teacher($Teacher);
}

In route file i have this code

$prefix = '/api/v2/teachers';

$router->group([
   'prefix' => $prefix,
   'namespace' => 'CarApp',
], function () use ($router) {

$router->get('/{Teacher}', 'TeacherController@show');
$router->get('/', 'TeacherController@list');

});

This is the error that i'm receiving when i'm doing get like this.

http://project.local/api/v2/teachers/1

{ "errors": { "type": "Symfony\Component\Debug\Exception\FatalThrowableError", "message": "Argument 1 passed to App\Http\Controllers\CarApp\TeacherController::show() must be an instance of App\CoursesApp\Teacher, string given", "code": 500 } }


Solution

  • Is the namespace suggestion of App\CoursesApp\Teacher correct in the error or are you looking for a model?

    If you are looking for something else, your use statement in your controller may be wrong.

    If that class App\CoursesApp\Teacher is not a model, Laravel cannot load it by primary key and cannot inject it properly meaning it will just pass "1" as a string.