Often in your form, you will need to populate the data directly from the database. This is usually the case when you have a one to many or many to many relationship established between your models and you want to persist the relationship data on form submission.

For this Example let's consider a Product model which has a one to one relationship with Category Model.

Consider a Form to Add new Product into the database. In our form, we would want the ability to select the category which the product belongs to.


<?php

namespace App\Http\Controllers\Admin;

use App\Category;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ProductController extends Controller
{

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $categories = Category::all(['id','name']);
        return view('products.create',compact('categories'));
    }
}

As you see, in the create method we get all the categories and pass it on to the product create page.

And here is how you can render the dropdown in your view page.

<div class="form-group">
    <label for="name">Category</label>
    <select class="form-control">
      @foreach($categories as $category)
        <option value="{{$category->id}}">{{$category->name}}</option>
      @endforeach
    </select>
  </div>
Comments