Home > Mobile >  Laravel Model data not available in Controller
Laravel Model data not available in Controller

Time:01-21

I'm new to Laravel. I might be making a basic mistake here but I've been trying and researching for a while, need some guidance here.

I have 2 routes:

Route::get('ordercontents/{ordercontent}', 'App\Http\Controllers\OrderContentsController@edit');

Route::get('ordercontents/delete/{ordercontents}', 'App\Http\Controllers\OrderContentsController@destroy');

Inside OrderContentsController.php I have the 2 functions, one to edit a record and another to delete it.

public function edit(\App\Models\Order_content $ordercontents)
    {
        dd($ordercontents); //the attributes will come out empty
        $orderContentId = $ordercontents->id;
        $ocs = getOrderContentDetails($orderContentId);
        return view('ordercontents.edit')->with('ordercontents', $ocs);
    }

public function destroy(\App\Models\Order_content $ordercontents)
    {
        $orderId = $ordercontents->order_id;
        $ordercontents->delete();
        return redirect('/new-ordercontent/' . $orderId)->with('success', 'Material removido da ordem de serviço!');
    }

The model exists and is called Order_content. Everything works well for the destroy function. However, I'm struggling with the edit function. If I do a dd($ordercontents); the attributes array of the object comes empty inside the edit function. What am I missing? Thanks!

CodePudding user response:

You have to make sure the name of the variable that is type-hinted in your method signature matches the route parameter for Route Model Binding:

"Laravel automatically resolves Eloquent models defined in routes or controller actions whose type-hinted variable names match a route segment name." - Laravel Docs

The method signature for edit can be adjusted to match the route parameter name:

public function edit(\App\Models\Order_content $ordercontent)

When these do not match you will have Dependency Injection happening so a new non-existing Model instance would be injected.

Laravel 8.x Docs - Routing- Route Model Binding - Implicit Binding

  •  Tags:  
  • Related