Route model binding not working on route group in laravel
Suppose I have these routes:
$api->group(['prefix' => 'Course'], function ($api) {
$api->group(['prefix' => '/{course}'], function ($api) {
$api->post('/', ['uses' => 'CourseController@course_details']);
$api->post('Register', ['uses' => 'CourseController@course_register']);
$api->post('Lessons', ['uses' => 'CourseController@course_lessons']);
});
});
As you can see all the routes /
, Register
and Lessons
prefixed with the desired parameter course
.
course
the parameter is the ID of the model course
that I want to use to bind the route model.
But on the other hand, when I want to use a parameter course
, for example in a function course_details
, it returns null
. eg:
public function course_details (\App\Course $course)
{
dd($course);
}
But if I use below everything works fine:
public function course_details ($course)
{
$course = Course::findOrFail($course);
return $course;
}
It doesn't seem to be able to bind the model correctly.
What is the problem?
Update:
Actually I am using the laravel dingo-api package to create an API. all routes are defined based on its configuration.
But there is a problem with routing model binding, where to support binding to the routing model, we have to add named middleware binding
for each route that needs model binding. HERE is described.
The big problem that exists is when I want to add middleware binding
to a route group it doesn't work and I have to add it to each of the routes.
In this case, I don't know how to solve the problem.
Decision:
After a lot of Googling I found that:
I found that I must add middleware bindings
to the same route group that added the middleware auth.api
, instead adding it to each additional route separately.
means the following:
$api->group(['middleware' => 'api.auth|bindings'], function ($api) {
});
Look carefully:
// Here $course is the id of the Course
public function course_details ($course)
{
$course = Course::findOrFail($course);
return $course;
}
But here:
// Here $course is the object of the model \App\Course
public function course_details (\App\Course $course)
{
dd($course);
}
which should be
public function course_details ($course, \App\Course $_course)
{
// add your model here with object $_course
// now $course return the id in your route
dd($course);
}
As you said
Course parameter is the course ID
You can use Request
to get the id, try this
public function course_details (Request $request)
{
return dd($request->course);
}
I faced similar problem. I think you need to use the 'bindings' middleware in your routes. See my answer here:
fooobar.com/questions/10136354 / ...