Sunday, May 21, 2017

Laravel inverse relation

So i have two tables:

Schema::create('goods', function (Blueprint $table) {
                $table->increments('id');
                $table->string('name');
                $table->integer('amount');
                $table->integer('shop_id');
                $table->timestamp('onPurchase');
                $table->timestamps();
        });
      
Schema::create('shops', function (Blueprint $table) {
                $table->increments('id');
                $table->string('name');
                $table->string('adress')->nullable();
                $table->timestamps();
        });

I want to print list of all goods and add name of the shop to every line of the good. When route opens this function runs:

function toBuy(){
        $good = Good::all();
        $data ['good'] = $good;
        return view('tobuy', $data);
    }

Blade:

@foreach ($good as $ginfo)
                                <tr>
                                        <td></td>
                                        <td></td>
                                        <td>
                                        @foreach ($ginfo->shop as $shop)
                                                
                                        @endforeach
                                        </td>
                                        <td>
                                        <a href="" type="submit" class="btn btn-default">Delete</a>
                                        </td>
                                </tr>
                                @endforeach

So how do i form a proper relationship using models Good and Shop and print what i need. Tried many ways and failed. Please help.



via Benua

Advertisement