Laravel 8- Eloquent Relationships  Tutorial - One to One Relationship
Tags: php, laravel, erd, beginners
Published: 2022-02-06 03:59:30

This is Part 1 of our Laravel 8 - Eloquent Relationships Tutorial

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nzb6010gpt39bark74yo.PNG)

Setup:
Let's create the laravel app erd-app

```
composer create-project laravel/laravel erd-app
cd erd-app
```
open .env and connect to your local database
`php artisan serve`


Then create students and profiles databases
`php artisan make:migration create_students_table`

go to app/database/migrations:

```
Schema::create('students', function (Blueprint $table) {
            $table->id();
            $table->string('first_name');
            $table->string('last_name');
            $table->timestamps();
        });
```
copy and save

`php artisan make:migration create_profiles_table`

go to app/database/migrations:

```
Schema::create('profiles', function (Blueprint $table) {
            $table->id();
            $table->foreignId('student_id');
            $table->string('email');
            $table->string('phone');
            $table->timestamps();
        });
```
copy and save

run migration to create tables
`php artisan migrate`
check in your database if successful

Now let's create the models student and profile
`php artisan make:model Student`
`php artisan make:model Profile`

> models should be singular while the table is plural


**One to One Relationships**

Go to app/Models and open the two newly created models

_define the one to one relationship_
in Models/Student.php 

```
protected $fillable = [
        'first_name',
        'last_name',
    ];

    public function profile()
    {
        return $this->hasOne('App\Models\Profile');
    }
```
in Models/Profile.php 

```
  protected $fillable = [
        'student_id',
        'email',
        'phone',
    ];

    public function student()
    {
        return $this->belongsTo('App\Models\Student');
    }
```
 _this will define the relationship between the two models_

Create the Controllers and Routes

`php artisan make:controller StudentController` 

go to app/Http/Controllers/StudentController

```
use App\Models\Student;

...

public function index(){
        $stu = Student::find(1);
        dd($stu);
    }

    public function store(){
        $student = new Student;
        $student->first_name = 'Dale';
        $student->last_name = 'Lanto';
        $student->save();
        dd($student);
    }
```

create routes in app/routes/web.php

```
Route::get('/students', [StudentController::class,'index'])->name('students');
Route::get('/students/store', [StudentController::class,'store'])->name('store');
```
in your browser go to http://localhost:8000/students/store to create 1 entry in the database

go to http://localhost:8000/students to check the models

it should look similar to:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/crb8bny1af0yshc5vhx4.PNG
)

Now lets create 1 entry for the profile

create new route

```
Route::get('/students/store/profile', [StudentController::class,'store_profile'])->name('storeProfile');
```
create new function in controller

```
public function store_profile(){

        $student = Student::find(1);

        $profile = new Profile;
        $profile->student_id = $student->id;
        $profile->email = 'dalelanto@gmail.com';
        $profile->phone = '7623423814';
        $profile->save();

        dd($profile);
    }
```
go to http://localhost:8000/students/store/profile to create 1 entry in the database

update the index function by calling profile from student

```
public function index(){
        $student = Student::find(1);
        dd($student->profile);
    }
```
go to http://localhost:8000/students to check 

it should look similar to:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3diri1pkf6q6cc1karc9.PNG)

> Hurray! We have successfully created our One to One Relationship.

For best practices it is best to include the foreign_key and local_key/owner_key in the model.

Let's go to Models/Profile.php and change the code to this

```
public function student()
    {
        // return $this->belongsTo('Model', 'foreign_key', 'owner_key'); 
        return $this->belongsTo('App\Models\Student','student_id','id');
    }

```

Now let's access the profile from the student model

```
public function index(){
        $student = Student::with('profile')->get();
        dd($student);
    }
```
Result:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tb8klk818n6t2e9bpxam.PNG)

> Click this [link](https://dev.to/dalelantowork/laravel-8-eloquent-relationships-tutorial-one-to-many-relationship-58j2) to proceed with the next tutorial - One to Many Relationship!