In a relational database management system, you know that database tables are often related to one another. For example, a country may have many states could be related to the country who state it country wise. Laravel eloquent makes managing and working with these relationships very convenient. Laravel provides many relationships and in this tutorial, we will see how we handle one to one or we can call this hasOne eloquent relationship.
What is One To One relationship?
A one-to-one relationship is a very basic type of database relationship. For example, a State model might be associated with one Countries model. To define this relationship, we will place a country method on the State model. The country method should call the hasOne method and return its result.
lets start one to one relationship in laravel step wise
we have already setup a laravel new project if you want to use same project the view or read previously tutorial and review that link below. after all setup laravel project.
Eloquent relationships are defined as methods in your Eloquent we will place a country method on the State model. We can use the hasOne() method to define one to one relationships and the first argument passed to the hasOne method is the country name of the related model class.
Step 1: Create a country methods on the State model
app/Models/State.php
Syntax :
// $this->hasOne(Model::class,'foreign_key','local_key');
// remember, foreign_key & local_key are optional
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class State extends Model
{
/**
* Get the country name associated with the state.
*/
public function country()
{
return $this->hasOne(Countries::class,'id','country_id');
}
}
Step 2: Use country methods on the State Controller
<?php
namespace App\Http\Controllers;
use App\Models\State;
use Illuminate\Http\Request;
class StateController extends Controller
{
public function index($id)
{
$state = State::find($id);
/**
* Get the country associated with the state.
*/
var_dump($state->country);
}
}
Why to use with in laravel ?
with() function is used to eager load in Laravel. Unless of using 2 or more separate queries to fetch data from the database , we can use it with() method after the first command. It provides a better user experience as we do not have to wait for a longer period of time in fetching data from the database.
Eloquent relationships fetch data using with() function
<?php
namespace App\Http\Controllers;
use App\Models\State;
use Illuminate\Http\Request;
class StateController extends Controller
{
public function index($id)
{
$state = State::with('country')->where(id,$id)->first();
/**
* Get the country associated with the state.
*/
var_dump($state->country);
}
}