dingo / api

A RESTful API package for the Laravel and Lumen frameworks.
BSD 3-Clause "New" or "Revised" License
9.33k stars 1.25k forks source link

Laravel 5.5 Resource routing can not bind model #1506

Open myloveGy opened 6 years ago

myloveGy commented 6 years ago
Q A
Bug? no
New Feature? yes
Framework Laravel
Framework version 5.5
Package version 2.0.0-alpha1
PHP version 7.0.20

Actual Behaviour

I do the following settings in the routing

$api->version('v1', ['namespace' => 'App\Http\Api\V1\Controllers'], function ($api) {
        $api->resource('applys', 'ApplysController');
});

I am on the controller below

public function destroy(Apply $apply)
    {
        return $apply;
    }

My request http://www.demo.com/api/applys/11 Get the structure is null, but in fact there is data But when I route the following settings, the structure is normal

Route::resource('applys', '\App\Http\Api\V1\Controllers\ApplysController');

And the following is also problematic

$api->version('v1', ['namespace' => 'App\Http\Api\V1\Controllers'], function ($api) {
        $api->get('applys/{applys}', function (\App\Models\Apply $apply) {
                return $apply->id; // The big one here is null
        })
});
mindonline commented 6 years ago

Laravel 5.6 same issue

mindonline commented 6 years ago

Adding bindings middleware to route group solve problem

lambasoft commented 3 years ago

The exact problem is still existing in Laravel 8. Adding bindings middleware causes the following error: Target class [bindings] does not exist.

federicorp commented 1 year ago

For future references,

Adding 'bindings' middleware as a group to all routes like explained here works in Laravel 9.39.0, BUT after configuring the Kernel.php as is said here and this other change also in the Kernel.php

I believe this solves @lambasoft problem also.

Basically you should do this:

api.php

$api = app('Dingo\Api\Routing\Router');

$api->version('v1', function ($api) {

    $api->group(['middleware' => 'bindings'], function($api) {

           $api->get('confirm-account/{token}', [ConfirmAccountController::class, 'confirm'])->name('confirm-account')
                 ->missing(fn() => response()->error(404, 'Token not found.'));
    });
});

Kernel.php

...
protected $middlewareGroups = [
    'web' => [
        ...
    ],

    'api' => [
        'throttle:api',
        'bindings',
    ],
];
...
protected $routeMiddleware = [
    ...
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ...
];