路由模型绑定不适用于 Laravel 中的路由组

A.B*_*per 5 php laravel laravel-5.4

假设我有这些路线:

$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']);
     });
});
Run Code Online (Sandbox Code Playgroud)

如您所见,所有/,RegisterLessonsroute 都以course必需参数为前缀。

course参数是Course我想用于路由模型绑定的模型的 ID 。

但另一方面,当我想coursecourse_details函数中使用参数 时,它返回null. 像这样 :

    public function course_details (\App\Course $course)
    {
        dd($course);
    }
Run Code Online (Sandbox Code Playgroud)

但是如果我在下面使用,一切正常:

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

        return $course;
    }
Run Code Online (Sandbox Code Playgroud)

似乎无法正确绑定模型。

什么是问题?

更新 :

事实上,我正在使用dingo-api laravel 包来创建 API。所有路由都基于它的配置定义。

但是有一个关于路由模型绑定的问题,我们必须binding为每个需要模型绑定的路由添加一个中间件来支持路由模型绑定。这里是描述它。

存在的一个更大的问题是,当我想将binding中间件添加到路由组时,它不起作用,我必须将它添加到每个路由中。

在这种情况下,我不知道如何解决问题。

解决方案:

经过多次谷歌搜索后,我发现:

我发现必须在添加bindings中间件的同一路由组中添加auth.api中间件,而不是将其分别添加到每个子路由中。
意思是这样的:

$api->group(['middleware' => 'api.auth|bindings'], function ($api) {
});
Run Code Online (Sandbox Code Playgroud)

小智 5

添加到kernel.php

 use Illuminate\Routing\Middleware\SubstituteBindings;
    protected $routeMiddleware = [
             ...
            'bindings' => SubstituteBindings::class,
        ];
Run Code Online (Sandbox Code Playgroud)

在您的团体路线中:

    Route::middleware(['auth:sanctum', 'bindings'])->group(function(){
    ... you routes here ...
    });
Run Code Online (Sandbox Code Playgroud)

这对我有用。谢谢


jog*_*_pi 0

仔细看看:

// Here $course is the id of the Course
public function course_details ($course)
{
    $course =   Course::findOrFail($course);
    return $course;
}
Run Code Online (Sandbox Code Playgroud)

但在这儿:

// Here $course is the object of the model \App\Course
public function course_details (\App\Course $course)
{
    dd($course);
}
Run Code Online (Sandbox Code Playgroud)

那应该是

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);
}
Run Code Online (Sandbox Code Playgroud)