One To One Relationship in Laravel

Limited Time Offer!

For Less Than the Cost of a Starbucks Coffee, Access All DevOpsSchool Videos on YouTube Unlimitedly.
Master DevOps, SRE, DevSecOps Skills!

Enroll Now

What is One To One relationships and usage of hasOne() and belongsTo() ?

  • One to one relationships are very straightforward in Laravel. Make sure that one of the tables has a key that references the id of the other table. For example, an ‘address’ table will have a field called user_id . That will reference the users_id field.
  • A one-to-one relationship exists when each row in one table has only one related row in a second table. For example, a business might decide to assign one office to exactly one employee. Thus, one employee can have only one office. The same business might also decide that a department can have only one manager.
  • A husband- wife relationship is the best example of One To One Relationship. There are two functions uses hasOne() and belongsTo(), both are related to each other. A belongsTo() relationship matches a related table’s ‘id’ to a ‘localKey’ field on ‘this’ model. Another way to think about it is the belongsTo() relationship should live on the model that has the field that links to the related tables id. Basic syntax of both uses in Models:
class Customer extends Model
{
  public function mobile()
  {
    return $this->hasOne(Mobile:class);      //customer and mobile relationship in a model/table.
  }
}
class Mobile extends Model
{

    public function customer()
    {
        return $this->belongsTo(Customer::class);   //relationship from mobile to customer
    }
}

How do I save a one to one relationship in laravel ?

  • Step 1 : Install Laravel and Basic Configurations. Each Laravel project needs this thing.
  • Step 2 : Create Migration and Model.
  • Step 3 : Setup One To One Relationship.
  • Step 4 : Inverse Of The Relationship.
  • Step 5 : Insert Records.
  • Step 6 : Retrieve Records.
  • Step 7: Update Records.
  • Step 8 : Delete Records.
  • Firstly create your laravel project and make two Models, Migrations and Conrollers by:
php artisan make:model Customer -mc
php artisan make:model Mobile -mc
  • Now goto both migration table & create a schema.
     Schema::create('customers', function (Blueprint $table)
         {
            $table->id();
            $table->string('name');                     //costomize
            $table->string('email');
            $table->timestamps();
        });
Schema::create('mobiles', function (Blueprint $table) {
            $table->id();
            $table->string('model');                             //costomize
            $table->timestamps();

            $table->unsignedBigInteger('customer_id');                   //customize to link id from          
            $table->foreign('customer_id')->references('id')->on('customers');
        });

See the migration table of customers & mobiles and also its foreign key & index. The id of customer_table to be extends in mobile_table.

  • Create a relation in Customer model b/w customer and mobile by hasOne() which are showing above, as well as create two method in CustomerController first insert the data after making both model object and showing the data.
    public function add_customer()

{

$customer = new Customer();
$customer->name="sam";
$customer->email="sam@gmail.com";
$customer->save();

$mobile = new Mobile();
$mobile->model = "oppo12";
$customer->mobile()->save($mobile); //save mobile on customer
return $customer;
}

In this Controller, create a another method to showing mobile_data from customer_id:

    public function show_mobile($id)

{
$mobile = Customer::find($id)->mobile;
return $mobile;

}
  • Goto routes ‘web.php’ & makes routes for customer and mobile to display one by one in url:
Route::get('add-customer',[CustomerController::class,'add_customer']);


Route::get('show-mobile/{id}',[CustomerController::class,'show_mobile']);
Route::get('show-customer/{id}',[MobileController::class,'show_customer']);
  • Similar, create a relation in Mobile model b/w mobile & customer by above belongsTo() and create a method in MobileController for showing data by mobile_id.
public function show_customer($id)

{
$customer = Mobile::find($id)->customer;
return $customer;
}

Finally there is relationship between Customer and Mobile. Remember we don’t forget to import both models in both controller class and controller in routes.

For Controllers:
use App\Models\Customer;
use App\Models\Mobile;
For routes:
use App\Http\Controllers\CustomerController;

use App\Http\Controllers\MobileController;