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) {
});
add in kernel.php
use Illuminate\Routing\Middleware\SubstituteBindings;
protected $routeMiddleware = [
...
'bindings' => SubstituteBindings::class,
];
and in your group route:
Route::middleware(['auth:sanctum', 'bindings'])->group(function(){
... you routes here ...
});
this worked for me. thanks
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With