How to Use One to Many Relationship in Laravel?

Laravel enables us to implement one to many relationship between tables in a very comfortable and easy way. Imagine we have products and categories table. Every product has one category and every category has many products. Now if want to get multiple products of any category then we will add following code in our category model.

app/Category.php 

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    protected $fillable = ['name'];

    public function products(){
    	return $this->hasMany('App\Product', 'category_id', 'id');
    }
}

Here product table has category_id as foreign key against primary key of categories table which is id. Now we can get products of category like this.

$category->products

This is very simple and convenient. If you have any problem while implementing it please leave a comment.