Laravel One to One Eloquent Relationship Example

Today, We want to share with you Laravel One to One Eloquent Relationship Example.
In this post we will show you laravel create one to one relation, hear for laravel eloquent one to one relationship we will give you demo and example for implement.
In this post, we will learn about laravel 5 one to one relationship with an example.

Laravel One to One Eloquent Relationship Demo

Laravel One to One Relationship will simple used To “hasOne()” as well as “belongsTo()” for some uniq relation.

Make Migrations:

teachers table migration:

Schema::create('teachers', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->string('email')->unique();
    $table->string('password');
    $table->rememberToken();
    $table->timestamps();
});

students table migration:
Schema::create('students', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('teacher_id')->unsigned();
    $table->string('student');
    $table->timestamps();
    $table->foreign('teacher_id')->references('id')->on('teachers')
        ->onDelete('cascade');
});

Make Models:

Teacher Model:

hasOne('App\Student');
    }
}

Student Model:
belongsTo('App\Teacher');
    }
}

Retrieve Records:

$student = Teacher::find(1)->student;
dd($student);

$teacher = Student::find(1)->teacher;
dd($teacher);

Create Records:

$teacher = Teacher::find(1);
 
$student = new Student;
$student->student = '9898225076';
 
$teacher->student()->save($student);

$student = Student::find(1);
 
$teacher = Teacher::find(10);
 
$student->teacher()->associate($teacher)->save();

Read :

READ :  Laravel Eloquent Join Multiple Table
jQuery 15 Powerful Tips and Tricks for Developers and Web Designer

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about laravel belongsto one to one relationship.
I would like to have feedback on my Infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Add a Comment

Your email address will not be published. Required fields are marked *