database screen t

How To Use One to One Relationship in Laravel?

Imagine we have categories table and category model and every category denoted by a name. Now we have products’ table with Product models. Every product will have a distinct name, price, description and category.

Category will be stored in products as category_id. Now as every product belongs to one and only one category so we can say products and categories have one to one relationship. It is very easy to implement in Laravel.

Here is our Product model.

app/Product.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $fillable = ['name', 'price', 'description', 'category_id'];

    public function category(){
    	return $this->belongsTo('App\Category','category_id', 'id');
    }
}

We added category() method and mentioned returned belongTo() in there with parameters. Now If we want to get category of any product then we can use this simple query.

$product->category->name

This will return category name of any product. This is very simple and easy. If you have any problems please leave a comment.