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)
如您所见,所有/
,Register
和Lessons
route 都以course
必需参数为前缀。
course
参数是Course
我想用于路由模型绑定的模型的 ID 。
但另一方面,当我想course
在course_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)
这对我有用。谢谢
仔细看看:
// 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)
归档时间: |
|
查看次数: |
1302 次 |
最近记录: |