One To One Relationship in Laravel

DevOps

MOTOSHARE 🚗🏍️
Turning Idle Vehicles into Shared Rides & Earnings

From Idle to Income. From Parked to Purpose.
Earn by Sharing, Ride by Renting.
Where Owners Earn, Riders Move.
Owners Earn. Riders Move. Motoshare Connects.

With Motoshare, every parked vehicle finds a purpose. Owners earn. Renters ride.
🚀 Everyone wins.

Start Your Journey with Motoshare

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.
  }
}Code language: JavaScript (javascript)
class Mobile extends Model
{

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

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 -mcCode language: CSS (css)
php artisan make:model Mobile -mcCode language: CSS (css)
  • 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();
        });Code language: PHP (php)
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');
        });Code language: PHP (php)

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;
   }Code language: PHP (php)

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;

        

     }Code language: PHP (php)
  • 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']);Code language: PHP (php)
  • 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;  


    }Code language: PHP (php)

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.

<strong>For Controllers</strong>:
use App\Models\Customer;

use App\Models\Mobile;Code language: PHP (php)
<strong>For routes:</strong>
use App\Http\Controllers\CustomerController;

use App\Http\Controllers\MobileController;Code language: PHP (php)