Netra
Netra

Reputation: 338

Laravel 5 Populate a form from two different tables

I stumbled upon a problem while creating a CRUD application in Laravel 5. In the edit section of a product I have 2 inputs that are populated from 'products' table and I have a dropdown list that needs to be populated with data from the categories table. The problem is that I don't know how to aproch the dropdown list. I generated the Form::model for the two inputs but I'm stuck at the dropdown list.

Controller

public function edit($id)
{
    $products_edit = products::find($id);

    return View::make('products.edit')->with('products_edit', $products_edit);
}

View

{!! Form::model($products_edit, array('route' => array('products.update', $products_edit->id), 'method' => 'PUT')) !!}

<div class="form-group">
    {!! Form::label('name', 'Nume') !!}
    {!! Form::input('text', 'name', $products_edit->product_name, array('class' => 'form-control')) !!}
</div>

<div class="form-group">
    {!! Form::label('price', 'Cost') !!}
    {!! Form::input('number', 'price', $products_edit->product_price, array('class' => 'form-control')) !!}
</div>

<div class="form-group">
    {!! Form::label('category', 'Categorie') !!} <br />
    {!! Form::select('category', <!-- insert var here -->, array('class' => 'form-control') !!}
</div>

Upvotes: 0

Views: 1575

Answers (2)

Mas Hary
Mas Hary

Reputation: 96

your can do thi controller:

public function edit($id)
{
    $products_edit = Product::find($id);
    $categories = Category::pluck('name', 'id');
    return view('product.edit', compact('products_edit', 'categories'));
}

Upvotes: 0

Gustavo Gama
Gustavo Gama

Reputation: 91

You can do this at your controller:

public function edit($id)
{
    $products_edit = Product::findOrFail($id);
    $categories = Category::lists('name', 'id');

    return view('product.edit', compact('products_edit', 'categories'));
}

In the view you still make the form model bind:

{!! Form::model($products_edit, array('route' => array('products.update', $products_edit->id), 'method' => 'PUT')) !!}

And to create the category dropdown try this:

{!! Form::label('category_id', 'Category') !!}
{!! Form::select('category_id', $categories, null, ['class' => 'form-control']) !!}

Upvotes: 3

Related Questions