Laravel

Laravel Eloquent One To One Relationships

Laravel Eloquent One To One Relationships
Written by ProgrammingPot

Laravel Eloquent One To One Relationships with Example From Scratch is today’s leading topic. Laravel is famously known as an Eloquent ORM which is Object-Relational Mapper. In this tutorial, we will see how One To One Relationship in Laravel 5.5 is working with an example.

Prerequisites

If you are new in Laravel 5.5 Eloquent Relationships, then check out my Laravel Eloquent Relationships Tutorial article in this blog.

Laravel Eloquent One To One Relationships


A one-to-one relationship is a fundamental relation. For example, User model has only one Blog Post, so he has just one post. So we can connect both models User and Post as a one to one relationship with each other. We can place post method into User model class, and that post belongs to only one User.  So in the User model, we can call post method and that one call hasOne method.

Example

We are defining the one to one relationship with Post and User. So first we need to set their schema.

Step 1: Make one schema for account details.

Go to the terminal and type the following command.

php artisan make:migration create_accounts_table

So, it will create one schema file in which, we need to define the columns like the following.

Post Table Schema

<?php
// create_posts_table
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->string('slug')->unique();
            $table->string('status');
            $table->integer('user_id');
            $table->integer('category_id');
            $table->integer('view');
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

User Table Scheme

<?php
// create_users_table
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email');
            $table->string('password');
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

Step 2: Migrate the Table or Create Table

Next, type the following command for migrate the both table and its relationship.

php artisan migrate

It will create all tables in the database.

Step 3: Make the Post.php Model

Make one model called Post.php by typing this command.

php artisan make:model Post

Then your Post.php model looks like,

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    //
}

Step 4: Defining Laravel Eloquent One To One Relationships

Now, In User.php Model, write the following function to define the relationship with the Post model.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * Get the post record associated with the user.
     */
    public function post()
    {
        return $this->hasOne('App\Post');
    }
}

The first argument passed to the hasOne method is the name of the related model. Once the relationship is defined, we may retrieve the related record using Eloquent’s dynamic properties. Dynamic properties allow you to access relationship methods as if they were properties defined on the model:

$phone = User::find(1)->phone;

Eloquent determines the foreign key of the relationship based on the model name. In this case, the Post model is automatically assumed to have a user_id foreign key. If you wish to override this convention, you may pass a second argument to the hasOne method:

return $this->hasOne('App\Post', 'foreign_key');

Additionally, Eloquent assumes that the foreign key should have a value matching the id (or the custom $primaryKey) column of the parent. In other words, Eloquent will look for the value of the user’s id column in the user_id column of the Post record. If you would like the relationship to use a value other than id, you may pass a third argument to the hasOne method specifying your custom key:

return $this->hasOne('App\Post', 'foreign_key', 'local_key');

Step:5 An Inverse Of The Relationship.

So, we can access an Post model from the User. Now, let’s define a relationship on an Post model that will allow us to obtain a User that owns an account. We can determine the inverse of the hasOne relationship using the belongsTo method.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    /**
     * Get the user that owns the phone.
     */
    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

In the example above, Eloquent will try to match a user_id from an Post model to an id on the User model. An Eloquent ORM determines a default foreign key name by examining the name of a relationship method and suffixing the method name with _id. However, if a foreign key on the Post model is not a user_id, you may pass the custom key name as the second argument to a belongsTo method.

Finally, our tutorial on Laravel Eloquent One To One Relationships is over. Happy Coding.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.