Search code examples
laravelmodelresourcesauto

Laravel Resources doesn't work with model binding on custom url


If i use this route:

Route::resource('monitor', 'UserMonitorController');

And then in controller:

public function update(Request $request, UserMonitor $userMonitor) {}

Which was automatically generated by

php artisan make:model -mcr UserMonitor

The $userMonitor is empty


Solution

  • Problem

    The reason is using route patch

    /monitor

    instead of

    /usermonitor (as controller name)

    Solution

    The variable has to be the same as variable in routing. In this case it's automatically generated:

    php artisan route:list 
    PUT|PATCH | api/monitor/{monitor}         | monitor.update    | App\Http\Controllers\UserMonitorController@update
    

    So the solution is to change:

    public function update(Request $request, UserMonitor $userMonitor) {}
    

    To:

    public function update(Request $request, UserMonitor $monitor) {}