Netra
Netra

Reputation: 338

Laravel 5 Pass data from two tables to the view

I'm using Laravel to create a CRUD application but I'm a little stuck. What I want to do is to display the coresponding Category from 'categories' table for each Product from the 'products' table. I tried to squeeze the two tables in one view and create a @foreach within the @foreach but that only listed all the categories instead of assigning the coresponding category based on the category_id from the products table.

Controller

$products = products::all();
$categories = categories::all();

return View::make('products.index')->with('products', $products)->with('categories', $categories);

View

@foreach($products as $key => $value)
    <tr>
        <td>{!! $value->id !!}</td>
        <td>{!! $value->product_name !!}</td>
        @foreach($categories as $key2 => $value2)
            <td>{!! $value2->category !!}</td>
        @endforeach
        <td>{!! $value->product_price !!}</td>
        <td>{!! $value->updated_at !!}</td>
        <td>
@endforeach

products table

    Schema::create('products', function($table)
    {
        $table->increments('id');
        $table->integer('category_id')->unsigned()->nullable();
        $table->string('product_name', 255)->unique();
        $table->decimal('product_price', 10, 4);
        $table->dateTime('updated_at')->default(DB::raw('CURRENT_TIMESTAMP'));
    });

    Schema::table('products', function($table) {
        $table->foreign('category_id')->references('id')->on('categories');
    });

categories table

    Schema::create('categories', function($table)
    {
        $table->increments('id');
        $table->string('category', 255)->unique();
        $table->dateTime('updated_at')->default(DB::raw('CURRENT_TIMESTAMP'));
    });

Upvotes: 3

Views: 6532

Answers (1)

Don&#39;t Panic
Don&#39;t Panic

Reputation: 41820

You can use a join to get the category for each product in one query.

$products = DB::table('products')
    ->join('categories', 'products.category_id', '=', 'categories.id')->get();

If each product has only one category, then your view can be simplified.

@foreach($products as $key => $value)
    <tr>
        <td>{!! $value->id !!}</td>
        <td>{!! $value->product_name !!}</td>
        <td>{!! $value->category !!}</td>
        <td>{!! $value->product_price !!}</td>
        <td>{!! $value->updated_at !!}</td>
    </tr>
@endforeach

Upvotes: 2

Related Questions