DEV Community

Sospeter Mong'are
Sospeter Mong'are

Posted on

Retrieving and Displaying Associated Data in Laravel API Response

Introduction

When building an API with Laravel, it's common to have relationships between your models. In some cases, you may want to fetch and display associated data from related models in your API responses. In this article, we'll explore how to do this using Laravel's Eloquent ORM and eager loading.

Setting Up the Relationships

Before we can retrieve associated data, we need to define relationships between our models. For this example, we'll consider a scenario where we have three models: DonationProduct, Donation, and ProductCategory. The DonationProduct model has foreign keys to the Donation and ProductCategory models. Here's how to set up the relationships in your models:

DonationProduct Model

class DonationProduct extends Model
{
    public function donation()
    {
        return $this->belongsTo(Donation::class, 'donation_id');
    }

    public function productCategory()
    {
        return $this->belongsTo(ProductCategory::class, 'category_id');
    }
}
Enter fullscreen mode Exit fullscreen mode

Donation Model

class Donation extends Model
{
    public function donationProducts()
    {
        return $this->hasMany(DonationProduct::class, 'donation_id');
    }
}
Enter fullscreen mode Exit fullscreen mode

ProductCategory Model

class ProductCategory extends Model
{
    public function donationProducts()
    {
        return $this->hasMany(DonationProduct::class, 'category_id');
    }
}
Enter fullscreen mode Exit fullscreen mode

With these relationships in place, we can now retrieve and display associated data in our API response.

Eager Loading

Laravel's eager loading allows us to retrieve related data along with the main model. In our case, we'll use eager loading to fetch Donation and ProductCategory data for each DonationProduct.

Let's modify our index method in the DonationProductController to include the associated models' names in the JSON response:

public function index()
{
    $donationProducts = DonationProduct::with('donation', 'productCategory')->get();

    $data = $donationProducts->map(function ($donationProduct) {
        return [
            'id' => $donationProduct->id,
            'donation_id' => [
                'id' => $donationProduct->donation->id,
                'name' => $donationProduct->donation->name, // Replace 'name' with the actual field name in the Donation model
            ],
            'category_id' => [
                'id' => $donationProduct->productCategory->id,
                'name' => $donationProduct->productCategory->name, // Replace 'name' with the actual field name in the ProductCategory model
            ],
            'product_name' => $donationProduct->product_name,
            'created_by' => $donationProduct->created_by,
            'updated_by' => $donationProduct->updated_by,
            'created_at' => $donationProduct->created_at,
            'updated_at' => $donationProduct->updated_at,
        ];
    });

    return response()->json([
        'message' => 'Donation products retrieved successfully',
        'data' => $data,
    ]);
}
Enter fullscreen mode Exit fullscreen mode

In this code, we use with('donation', 'productCategory') to eager load the associated Donation and ProductCategory models for each DonationProduct. We then map the data to include the associated models' names in the JSON response.

Remember to replace 'name' with the actual field names in your Donation and ProductCategory models.

Conclusion

Retrieving and displaying associated data in Laravel API responses is a common requirement. By setting up relationships in your models and using eager loading, you can efficiently fetch and display related data, enhancing the quality and usability of your API.

Top comments (0)