Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Laravel Model data not available in Controller

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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."

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 just have Dependency Injection happening so a new non-existing Model instance would be injected.

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading