Benji40
Benji40

Reputation: 237

Laravel Passing Variable from Forms

I am brand new to Laravel, and following a super basic tutorial. However the tutorial did not come with an edit record section, which I am attempting to extend myself.

Route:

Route::controller('admin/products', 'ProductsController');

Controller:

class ProductsController extends BaseController
{ 

public function getUpdate($id)
    {
        $product = Product::find($id);

        if ($product) {
            $product->title = Input::get('title');
            $product->save();
            return Redirect::to('admin/products/index')->with('message', 'Product Updated');
        }
        return Redirect::to('admin/products/index')->with('message', 'Invalid Product');
}

..ECT...

I realise the controller is requesting an ID to use, but I cannot figure out how to pass it a product ID when the form is posted/get.

Form:

{{Form::open(array("url"=>"admin/products/update",'method' => 'get', 'files'=>true))}}
    <ul>
        <li>
            {{ Form::label('title', 'Title:') }}
            {{ Form::text('title') }}
            {{ Form::hidden('id', $product->id) }}

 ..ECT...

{{ Form::close() }}

my initial idea was to pass the product id within the form URL like:

{{Form::open(array("url"=>"admin/products/update/{{product->id}}", 'files'=>true))}}

But no luck with that either.

The error I get is:

Missing argument 1 for ProductsController::postUpdate()

Interestingly if I type directly into the URL:

http://localhost/laravel/public/admin/products/update/3

It works and the item with id 3 is altered fine.

So can anyone help and inform me how to pass the id with a form?

Thanks very much

Upvotes: 4

Views: 13672

Answers (1)

ITroubs
ITroubs

Reputation: 11215

The first Problem here ist the following:

{{Form::open(array("url"=>"admin/products/update/{{product->id}}", 'files'=>true))}}

the {{product->id}} is wrong in two ways:

  1. it should be {{$product->id}}
  2. BUT it wouldn't work anyway because the inner {{..}} inside of the {{Form::...}} won't be recognized since it is inside a string and therefore part of the string itself.

You either have to write it this way:

{{Form::open(array("url"=>"admin/products/update/".$product->id, 'files'=>true))}}

or you give your route a name in your routes.php file and do it this way:

{{Form::open(array('route' => array('route.name', $product->id, 'files'=>true)))}}

I prefer the second way.

You also might want to look into Form Model Bingin

Upvotes: 6

Related Questions