Search code examples
laravellaravel-routing

laravel resource function works correct but when i use it manualy doesent work


i am using laravel 5 when i use laravel Route::resource function in my route.php file i can get my model collection inside a parameter of my method like this:

     //**web.php** file

     Route::resource('factors', 'FactorsController');

     //called url localhost:8000/factors/1/edit

     //**FactorsController**

     /**
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
     public function edit(Request $request, Factor $factor)
     {
         //$factor is a collection of Factor Model that contains id '1' information in factor table

         return view('factors.edit', compact('factor'));
     }

it is correct and works but when i make a custom url like this:

Route::get('factors/{id}/newEdit', 'FactorsController@newEdit');

i can't get the collection inside method parameters and it returns empty collection like this:

 //called url localhost:8000/factors/1/newEdit

 1)
 //**FactorsController**

 /**
 * @param Request $request
 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
 */
 public function newEdit(Request $request, Factor $factor)
 {
     return view('factors.newEdit', compact('factor'));
 }

$factor is a empty collection of Factor Model but i want my selected row in database. when i use that like this works correct:

 2)
 //**FactorsController**

 /**
 * @param Request $request
 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
 */
 public function newEdit(Request $request, $id)
 {
     $factor = Factor::find($id);

     return view('factors.newEdit', compact('factor'));
 }

but i don't want to call it like 2 i want to call it like 1

thanks for any help.


Solution

  • For model binding, you should have type-hinted variable names match a route segment name :

    Route::get('factors/{factor}/newEdit', 'FactorsController@newEdit');
    

    Since the $factor variable is type-hinted as the Factor model and the variable name matches the {factor} URI segment, Laravel will automatically inject the model instance that has an ID matching the corresponding value from the request URI.