Home > Software engineering >  Why parameter set in put method is not passed?
Why parameter set in put method is not passed?

Time:11-27

Running activate method with sanctum id parameter I see that id parameter is not passed into activate control action. In routes/api.php :

Route::middleware('auth:sanctum')->group( function () {
    Route::post('logout', [AuthController::class, 'logout']);
    Route::resource('ads', AdController::class);
    Route::put('ads/{id}/activate', [AdController::class, 'activate']); 
});

In postman I pass parameter as http://server.com/api/ads/7/activate, but problem is that in app/Http/Controllers/API/AdController.php :

public function activate(Request $request, Ad $ad)
{
    \Log::info(varDump($ad->id, ' -1 activate $ad->id::')); // this parameter is null - and error next :
    ...
} // public function activate(Ad $ad)

In Laravel Telescope I see details :

Request Details
Time    November 26th 2021, 5:08:08 PM (1:46m ago)
Hostname    master-laptop
Method  PUT
Controller Action   App\Http\Controllers\API\AdController@activate
Middleware  api, auth:sanctum
Path    /api/ads/7/activate
Status  500
Duration    113 ms
IP Address  127.0.0.1
Memory usage    2 MB
Tags    Auth:10

Why id parameter is wrong ?

    "laravel/framework": "^8.26.1",
    "laravel/sanctum": "^2.8",

Thanks in advance !

CodePudding user response:

You need to use route binding you need to replace {id} to {ad}

Route::put('ads/{ad}/activate', [AdController::class, 'activate']);

If your issues is still not solved you can manually do it. Add this code to boot method of RouteServiceProvider

Route::model('ad', Ad::class);

CodePudding user response:

As mentioned in the comments, to get Implicit binding to work the uri segment in the route must match the parameter (variable) name of the method e.g.

Change {id} to {ad} so that it matches the $ad parameter of the activate method:

Route::put('ads/{ad}/activate', [AdController::class, 'activate']);
  • Related