lozadaOmr
lozadaOmr

Reputation: 2655

Get the model ID when updating a resource

I have a form that will submit a Patch request to the controller's update method. But the update method requires to have $id, as you can see below whenever I try that I get a No query results for model [Item]. Since the update method did not receive the $id of the model

public function update($id)
    {
        $item = Item::findOrFail($id);
        $update = Input::all();
            // some codes to save changes

        return Redirect::route('items.index');
    }

Another thing is that whenever I submit the form, url turns into something like this:

mw.dev/items/%7Bitems%7D


Edit

routes.php

Route::resource('items','ItemsController');

ItemController

public function edit($id)
    {
        $item = Item::findOrFail($id);
        return View::make('items.edit')->with('item',$item);
    }

I have included the code on my edit.blade.php

{{Form::open(array('route' => 'items.update', 'method'=>'patch'))}}
    {{Form::text('barcode', $item->barcode, array('placeholder' => 'barcode'))}}
    {{Form::text('imei',$item->imei, array('placeholder' => 'imei'))}}
    {{Form::text('item_name', $item->item_name, array('placeholder' => 'item name'))}}
    {{Form::submit('edit')}}
{{Form::close()}}

Upvotes: 0

Views: 2003

Answers (2)

The Alpha
The Alpha

Reputation: 146201

You have to pass the model to your view and need to pass the id parameter when generating the form. Assume that you have a User model and it's available in the view. So you may generate the form action using something like this:

// Using Form::open method with route
Form::open(array('route' => array('route.name', $user->id)))

// Using Form::model method with route
Form::model($user, array('route' => array('route.name', $user->id), 'method' => 'patch'))

// Using Form::open method with action
Form::open(array('action' => array('Controller@update', $user->id), 'method' => 'patch'))

// Using Form::open method with url
Form::open(array('url' => 'something/update/' . $user->id, 'method' => 'patch'))

Check more on Opening A Form.

Upvotes: 1

Cranio
Cranio

Reputation: 9847

The URL

mw.dev/items/%7Bitems%7D

is most likely the url-encoded form of

mw.dev/items/{items}

I suppose there is a problem in the form submission or in the <form>'s action paremeter or in the Route::* declaration in routes.php.

This could also explain why you don't get any $id upon submission.

Upvotes: 0

Related Questions