In a relational database management system, you know that database tables are often related to one another. For example, a company may have many employees or an order could be related to the user who placed it. 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.
In this Laravel 9 one to one relationship example tutorial, I am going to use the User and Phone concept. Suppose, A user may have one phone and a phone may have one user. Let's see how we can define Laravel's one to one relationship.
Eloquent relationships are defined as methods in your Eloquent model classes. We can use the hasOne() method to define one to one relationships and the first argument passed to the hasOne method is the name of the related model class.
C:\xampp\htdocs\wayarmy\routes\web.php
<?phpuseIlluminate\Support\Facades\Route;useApp\Http\Controllers\TestControlleras TestController;/*|--------------------------------------------------------------------------| Web Routes|--------------------------------------------------------------------------|| Here is where you can register web routes for your application. These| routes are loaded by the RouteServiceProvider within a group which| contains the "web" middleware group. Now create something great!|*/Route::get('/',function () {returnview('welcome');});Route::get('test/{id}', [TestController::class,'index'])->name('index');Route::get('test2/{id}', [TestController::class,'index2'])->name('index2');
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Carbon\Carbon;
use Collective\Html\Eloquent\FormAccessible;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable, FormAccessible;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
public $timestamps = false;
protected $fillable = [
'name'
];
public function phone() {
return $this->hasOne(Phone::class,'user_id','id');
}
}
C:\xampp\htdocs\wayarmy\app\Models\Phone.php
<?phpnamespaceApp\Models;useIlluminate\Database\Eloquent\Factories\HasFactory;useIlluminate\Database\Eloquent\Model;classPhoneextendsModel{useHasFactory;/** * The attributes that are mass assignable. * * @vararray<int, string> */protected $fillable = ['user_id','phone' ];public $timestamps =false;publicfunctionuser() {return$this->belongsTo(User::class); }}
<?phpnamespaceApp\Http\Controllers;useApp\Models\User;useApp\Models\Phone;useIlluminate\Http\Request;classTestControllerextendsController{/** * Display a listing of the resource. * * @return\Illuminate\Http\Response */publicfunctionindex($id) { $user =User::find($id);/** * Get the phone associated with the user. */ $phone = $user->phone;dd($phone->phone); }publicfunctionindex2($id) { $phone =Phone::find($id);/** * Get the phone associated with the user. */ $name = $phone->user;dd($name->name); }}
<?phpuseIlluminate\Database\Migrations\Migration;useIlluminate\Database\Schema\Blueprint;useIlluminate\Support\Facades\Schema;classCreateUsersTableextendsMigration{/** * Run the migrations. * * @returnvoid */publicfunctionup() {Schema::create('users',function (Blueprint $table) { $table->id(); $table->string('name'); }); }/** * Reverse the migrations. * * @returnvoid */publicfunctiondown() {Schema::dropIfExists('users'); }}
In a relational database management system, you know that database tables are often related to one another. For example, a company may have many employees or an order could be related to the user who placed it. 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.
In this Laravel 9 one to one relationship example tutorial, I am going to use the User and Phone concept. Suppose, A user may have one phone and a phone may have one user. Let's see how we can define Laravel's one to one relationship.
Eloquent relationships are defined as methods in your Eloquent model classes. We can use the hasOne() method to define one to one relationships and the first argument passed to the hasOne method is the name of the related model class.
Assume that one user may have one Phone. So we can define this relationship like this:
app/Models/User.php
<?phpnamespaceApp\Models;useIlluminate\Database\Eloquent\Model;classUserextendsModel{/** * Get the phone associated with the user. */publicfunctionphone() {// $this->hasOne(Model::class,'foreign_key','local_key');// remember, foreign_key & local_key are optionalreturn$this->hasOne(Phone::class,'user_id','id'); }}
PHPCopy
Now we can fetch every user's phone information from the controller like:
App\Http\Controllers\TestController.php
<?phpnamespaceApp\Http\Controllers;useApp\Models\User;useIlluminate\Http\Request;classTestControllerextendsController{publicfunctionindex($id) { $user =User::find($id);/** * Get the phone associated with the user. */ $user->phone; }}
PHPCopy
Defining Inverse Relationship of hasOne
Now we know how to define hasOne or one to one relationship. Now we will see how we can define the inverse relationship of hasOne. Let's define a relationship on the Phone model that will let us access the user that owns his/her phone. We can define the inverse of a hasOne relationship using the belongsTo method like:
app/Models/Phone.php
<?phpnamespaceApp\Models;useIlluminate\Database\Eloquent\Model;classPhoneextendsModel{/** * Get the user that owns the phone. */publicfunctionuser() {return$this->belongsTo(User::class); }}