Understanding one-to-one relationship in Laravel

February 11, 2018 By - Usama Muneer | 899

    Introduction

    If you want your table to have literally one of anything, then one-to-one is the most simplest relationship. For instance, a token is generated for resetting a user password & its a simple one-to-one relationship between users and password_resets table.

    Without wasting much time in theoretical talks, let’s straight dive into a more practical example & try to understand one-to-one relationships in Laravel.

    Example

    In the below example, we’ll have a look on the very basic relationship between a user & his contact number. For instance, in this case, a user may only have one contact number associated with him.

    – Setting up Configurations

    Setup your Database configuration settings in your .env file.

    – Auth Scaffolding

    Laravel provides the basic authentication out of the box & generates all the necessary files by running this simple artisan command.

    php artisan make:auth

    – Setting up contact number model & migration

    We’ll use artisan CLI to generate contact number model & migration file for us.

    php artisan make:model ContactNumber -m

    – Edit the Migration File

    Inside of our create_contact_numbers_table migration file, which you may find under database/migrations folder.

    Schema::create('contact_numbers', function (Blueprint $table) {
        $table->increments('id');
        //contact number belongs to a user
        $table->integer('user_id')->unsigned();
        $table->string('contact_number');
        $table->timestamps();
    });

    and finally run the migrations like so,

    php artisan migrate

    – Setting up the Relationship

    As we know that, our user can have one contact number, so we’ll setup this relationship inside of our User.php model.

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function contactNumber() {
       return $this->hasOne( 'App\ContactNumber' );
    }

    Now as the relationship is all set, technically a user can now insert a contact number, update his contact number and delete his contact number.

    – Testing the relationship

    We’ll test this relationship out with Laravel tinker.

    php artisan tinker

    > $user = factory('App\User')->create();

    Currently if we try to access contactNumber property from user instance, we’ll get null in return.

    > $user->contactNumber;

    Let’s assign a contact number to this user.

    > $user->contactNumber()->create([
    'contact_number' => '+92324334213'
    ]);
    Note: You may see a mass assignment exception with create method here. You just need to define the fillable columns inside of your ContactNumber model like so,
    //ContactNumber.php

    protected $fillable =[‘contact_number’];

    We can achieve the same with the other way around as well & without defining the fillable fields, like so,

    > $cNo = new App\ContactNumber();
    > $cNo->contact_number = '+92324334213';

    But you must be thinking that this must have to be associated to a user? Well here comes the reverse relationship.

    > $cNo->user()->associate($user);

    > $cNo->save();

    – Setup the Reverse Relationship

    Inside of our ContactNumber model, we can define our reverse relationship with user, which means a contact number may belongs to a user instance like we’ve seen in the last example.

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function user() {
       return $this->belongsTo( 'App\User' );
    }

    Diving in a bit Deeper

    Now as we’ve seen the relationships have been set, we can now test out further on by grabbing user’s contact number one way or another by using simple queries.

    – Finding contact number

    > $cNo = ContactNumber::find(1);
    // returns the contact_number with the id of 1

    > $cNo = ContactNumber::where('contact_number','000000111')->first();
     //returns the contact_number where itsĀ 000000111 & gets the first records as its one to one relationship & we don't want a collection.

    – Eager loading the associated user

    Given we’ve a contact number, we need to get the user associated with that contact number, well there are multiple ways to do so.

    > $cNo->user()->first()->name;
    //Directly calling the user collection & getting the name property.

    Or

    > $cNo->user->name;
    //eager load for omitting the N+1 issues.

    Conclusion

    We hope we’d make the one to one relationship a bit clearer to you with the above examples. Let us know in the comments section below if you have any queries regarding this approach.

    Follow us on Twitter.

    blog user
    Usama Muneer

    A web enthusiastic, self-motivated & detail-oriented professional Full-Stack Web Developer from Karachi, Pakistan with experience in developing applications using JavaScript, WordPress & Laravel specifically. Loves to write on different web technologies with an equally useful skill to make some sense out of it.

    Related Posts

    Another #LaraconUS in the books & It was the 6th instalment of #LaraconUS happened at Chicago with full swing & we got a lot to learn this time with exceptional line of speakers and never-ending community support by fellow Artisans

    Laravel is one of a famous and widely used PHP framework which is growing with immense pace since its version 4.2. Learning Laravel & Setting up your application locally is not much of a difficult task but when it comes to deployment, developers often find it a bit tricky to handle.

    There are several PHP frameworks for a web development project. Among them Laravel is regarded as the best open-source PHP web framework.

    If you've no idea what macroable functionality is, take it as something you want to extend in within Laravel with a piece of code that doesn't exists in the Class.