lmartins
2 years ago

Pull models from relationship data

Posted 2 years ago by lmartins

Hi,

Just starting with Laravel, so please be patient with what might be an obvious question.

I have a model "Organization" that is linked to many purchases in its model:

public function purchases(){
        return $this->hasMany(Purchase::class)->orderBy('created_at','DESC');
    }

The purchases table include a foreign key for another table "Products", like this:

Schema::create('purchases', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('credits')->unsigned();
            $table->integer('product_id')->unsigned();
            $table->foreign('product_id')
                    ->references('id')
                    ->on('products');
            $table->integer('organization_id')->unsigned();
            $table->foreign('organization_id')
                    ->references('id')
                    ->on('organizations');
            $table->timestamps();
        });

When I'm listing the purchases on the frontend, I'd like to show the linked product to each purchase, instead of it's ID, how could one achieve that?

        @if( count($organization->purchases) )
            <section class="Section">
                <header class="Section__header">Purchases</header>
                @foreach($organization->purchases as $purchase)
                    <li>
                        {{ $purchase->created_at->diffForHumans() }} |
                        {{ $purchase->product_id }} |
                        {{ $purchase->credits }} Credits
                    </li>
                @endforeach
            </section>
        @endif

Please sign in or create an account to participate in this conversation.