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:
[php]
Schema::create(‘teachers’, function (Blueprint $table) {
$table->increments(‘id’);
$table->string(‘name’);
$table->string(’email’)->unique();
$table->string(‘password’);
$table->rememberToken();
$table->timestamps();
});
[/php]
students table migration:
[php]
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’);
});
[/php]
Make Models:
Teacher Model:
[php]
hasOne(‘App\Student’);
}
}
[/php]
Student Model:
[php]
belongsTo(‘App\Teacher’);
}
}
[/php]
Retrieve Records:
[php]
$student = Teacher::find(1)->student;
dd($student);
[/php]
[php]
$teacher = Student::find(1)->teacher;
dd($teacher);
[/php]
Create Records:
[php]
$teacher = Teacher::find(1);
$student = new Student;
$student->student = ‘9898225076’;
$teacher->student()->save($student);
[/php]
[php]
$student = Student::find(1);
$teacher = Teacher::find(10);
$student->teacher()->associate($teacher)->save();
[/php]
Read :
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.