Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Route Model Binding does not work 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 / , 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) {
});
like image 463
A.B.Developer Avatar asked Nov 08 '22 22:11

A.B.Developer


2 Answers

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

like image 83
Sanjok Dangol Avatar answered Nov 14 '22 22:11

Sanjok Dangol


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);
}
like image 39
Niklesh Raut Avatar answered Nov 14 '22 22:11

Niklesh Raut