Search code examples
laraveleloquentormmodelmany-to-many

PHP Laravel Eloquent ORM. How to test table relantionship (belongsToMany)


I'm currently building an API assigned for an ecommerce project using Laravel framework. While getting help to build data migrations and Models, I got confused on how the product_categories, the intermediate table, can link a product and category as in the many to many relantionship (products <-> product_categories <-> category). These are the models in development:

project models

This is the category class: class Category extends Model

class Category extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
    ];

    public function products()
    {
        return $this->belongsToMany(
            Product::class,
            ProductCategory::class,
        );
    }
}

And the product Model

class Product extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'slug',
        'price',
        'active',
    ];

    protected $casts = [
        'price' => 'float',
        'active' => 'boolean',
    ];


    public function categories() 
    {
        return $this->belongsToMany(
            Category::class,
            ProductCategory::class
        );
    }

    public function orderItems()
    {
        return $this->hasMany(
            OrderItem::class,
        );
    }
}

As I'm still new at this I couldn't understand from the documentation what makes a product and category be linked neither how the Order Model should look like.

I'm using postman to make requests and they work with the current controllers. So my doubt is actually conceptual instead of technique.


Solution

  • You can create a simple controller like the one below:

    public function index()
    {
        $product = Product::with('categories')->get();
    
        return response()->json([
            'data' => $product
        ]);
    }
    

    From the code above, all related data for each product category should be retrieved. If you are using Eloquent, you don't need to perform joins, which will make the process more time-efficient.