In this tutorial, today we discuss laravel one to one Eloquent relationship. Eloquent ORM means Object-relational Mapping and laravel provides a beautiful ActiveRecord structure. so we can easy to interact with the application database. let’s start about one to one eloquent relationship.

Laravel one to one relationship is based on the relation between two tables. so we need one table of the primary key and another table of reference key. For example, we have two tables: Students and Standards. both tables are connected as a one to one relationship with each other using the primary key and reference key.

Setting Database Configuration

After complete installation of laravel. we have to database configuration. now we will open the .env file and change the database name, username, password in the .env file. See below changes in a .env file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=Enter_Your_Database_Name(one_to_one_relation)
DB_USERNAME=Enter_Your_Database_Username(root)
DB_PASSWORD=Enter_Your_Database_Password(root)

Create Table using migration

Now, We need to create a migration. so we will below command using create the students and standards table migration.

php artisan make:migration create_students_table --create=students
php artisan make:migration create_standars_table --create=standards

After complete migration. we need below changes in the database/migrations/create_students_table and database/migrations/create_standars_table file.

create_students_table.php

<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateStudentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('students', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('first_name');
            $table->string('last_name');
            $table->text('address');
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('students');
    }
}
?>

create_standars_table.php

<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateStandardsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('standards', function (Blueprint $table) {
            $table->bigIncrements('id');
			$table->integer('student_id')->unsigned();
            $table->string('standard_name');
            $table->timestamps();
			$table->foreign('student_id')->references('id')->on('students')->onDelete('cascade');
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('standards');
    }
}
?>

Run the below command. after the changes above file.

php artisan migrate

Create Model

Here below command help through we will create the Student and Standard model. we will also use “hasOne()” for a student model and “belongsTo()” for a standard model.

php artisan make:model Student
php artisan make:model Standard

Student.php

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Student extends Model
{
    protected $fillable = [
        'first_name','last_name', 'address'
    ];
	
	/**
     * Get the standard record associated with the student.
     */
    public function standard()
    {
        return $this->hasOne('App\Standard');
    }
}
?>

Standard.php

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Standard extends Model
{
    /**
     * Get the student that owns the standard.
     */
    public function student()
    {
        return $this->belongsTo('App\Student');
    }
}

?>

Route and Controller

We have to need put below student resource route in routes/web.

<?php
 
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
 
Route::get('/', function () {
    return view('welcome');
});
 
Route::get('student','studentsController@index');

?>

Here below command help to create the student controller.

php artisan make:controller StudentsController

StudentController.php

<?php
namespace App\Http\Controllers;
use App\Student;
use App\Standard;
use Illuminate\Http\Request;
class StudentController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
        $student1 = Student::find(1)->standard;
		dd($student1);
    }

}
?>