5
votes

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 / , Register and Lessons route prefixed by a course required parameter.

course parameter is a ID of a Course model that I want to use for route model binding.

But In the other hand when I want use course parameter for example in course_details function, it returns null. like this :

    public function course_details (\App\Course $course)
    {
        dd($course);
    }

But if I use below, all things worked fine :

    public function course_details ($course)
    {
        $course =   Course::findOrFail($course);

        return $course;
    }

Seems that it can not bind model properly.

What is Problem ?

Update :

In fact I'm using dingo-api laravel package to create an API. all routes defined based it's configuration.

But there is an issue about route model binding where to support route model binding we must to add a middleware named binding to each route that need model binding. HERE is described it.

A bigger problem that exists is when I want to add binding middleware to a route group, it does not work and I must add it to each of routes.

In this case I do not know how can I solve the problem.

Solution:

After many Googling I found that :

I found that must to add bindings middleware in the same route group that added auth.api middleware instead adding it to each sub routes separately.
means like this :

$api->group(['middleware' => 'api.auth|bindings'], function ($api) {
});
3

3 Answers

1
votes

As you said

course parameter is a ID of a Course

You can use Request to get id, try like this

public function course_details (Request $request)
{
    return dd($request->course);
}
0
votes

Take a close look on:

// 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);
}

that 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);
}
0
votes

I came across a similar issue. I think you need to use the 'bindings' middleware on your routes. See my answer here:

https://stackoverflow.com/a/55949930/2867894