Search code examples
laravelmodelcontrollerurl-routinglaravel-5.7

Laravel controller method with model as parameter


I created an model using php artisan make:model Transaction -a, so it generated a migration, factory, and resource controller for the model too. Everything working as expected, but I realized this in controller code:

/**
 * Display the specified resource.
 *
 * @param  \App\Transaction  $transaction
 * @return \Illuminate\Http\Response
 */
public function show(Transaction $transaction)
{
    //
}

/**
 * Show the form for editing the specified resource.
 *
 * @param  \App\Transaction  $transaction
 * @return \Illuminate\Http\Response
 */
public function edit(Transaction $transaction)
{
    //
}

Looks like it's expecting an model instance in show() and edit() methods, what seems to be a helper to return the view, but how can I integrate this in web routing?


English isn't my native language.


Solution

  • if your route is administração/transações/{transaçõe} and your model is Transaction then laravel doesn't know what to do with it!

    so to make it work, there are two ways:

    • you have to bind it explicity according to this link:

      add Route::model('transaçõe', App\Transaction::class); to boot() method of your RouteServiceProvider as follows:

      public function boot()
      {
          parent::boot();
      
          Route::model('transaçõe', App\Transaction::class);
      }
      
    • OR you change the route to administração/transações/{transaction}.