Laravel 9 One to One Relationship Example

Whatsapp

https://www.fundaofwebit.com/post/laravel-9-one-to-one-relationship-example

Laravel Eloquent One to One Relationship Example


Laravel 9 one to one relationship example; In this tutorial, you will learn what is one to one relationship and how to use one to one relationships in laravel with examples.

A one-to-one relationship is a very basic relation. And using one to one relationship, you can insert, retrieve, update, and delete data with the eloquent model from the database table in laravel.

Let's take an example of Student and Student_Details, so create students migration and student_details migration in the application.

Let's begin with One to One Relationship in laravel 9 


Step 1: Create 2 migration students and students_details migration with following command:

Student table migration: 

php artisan make:migration create_students_table

and after creating migration, paste the below code.

Schema::create('students', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->string('email');
    $table->string('phone');
    $table->timestamps();
});


Student Details table migration:

php artisan make:migration create_student_details_table

after creating migration, paste the below code: 

Schema::create('student_details', function (Blueprint $table) {
    $table->id();
    $table->unsignedBigInteger('student_id')->unique();
    $table->string('alternate_phone');
    $table->string('course');
    $table->string('roll_no');
    $table->foreign('student_id')->references('id')->on('students')->onDelete('cascade');
    $table->timestamps();
});


Step 2: Create 2 Models as Student and StudentDetail with the following command:

Create Student Model:

php artisan make:model Student

after creating this model, paste the below code in model:

<?php

namespace App\Models;

use App\Models\StudentDetail;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Student extends Model
{
    use HasFactory;

    protected $table = 'students';

    protected $fillable = [
        'name',
        'email',
        'phone'
    ];

    public function studentDetail()
    {
        return $this->hasOne(StudentDetail::class, 'student_id', 'id');
    }
}


Create StudentDetail Model:

php artisan make:model StudentDetail

after creating this model, paste the below code in model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class StudentDetail extends Model
{
    use HasFactory;

    protected $table = 'student_details';

    protected $fillable = [
        'student_id',
        'alternate_phone',
        'course',
        'roll_no'
    ];
}


Step 3: Lets Save/Insert data into database of student and student_details in many different method.:


Method 1: To Insert/Save data into database using one to one relationshiop in laravel:


Create a blade file in following path: resources/views/students/create.blade.php and paste the below form:

@extends('layouts.app')

@section('content')

<div class="container mt-4">
    @if (session('message'))
        <h4 class="alert alert-success">{{ session('message') }}</h4>
    @endif
    <div class="row">
        <div class="card">
            <div class="card-header">
                <h4>Add Student</h4>
            </div>
            <div class="card-body">
                <form action="{{ url('students') }}" method="POST">
                    @csrf

                    <div class="row">
                        <h4>Student</h4>
                        <div class="col-md-4 mb-3">
                            <label>Name</label>
                            <input type="text" name="name" class="form-control" />
                        </div>
                        <div class="col-md-4 mb-3">
                            <label>Email</label>
                            <input type="text" name="email" class="form-control" />
                        </div>
                        <div class="col-md-4 mb-3">
                            <label>Phone</label>
                            <input type="text" name="phone" class="form-control" />
                        </div>
                    </div>
                    <div class="row">
                        <h4>Student Details</h4>
                        <div class="mb-3 col-md-4">
                            <label>Alternate Phone</label>
                            <input type="text" name="alternate_phone" class="form-control" />
                        </div>
                        <div class="mb-3 col-md-4">
                            <label>Course</label>
                            <input type="text" name="course" class="form-control" />
                        </div>
                        <div class="mb-3 col-md-4">
                            <label>Roll No.</label>
                            <input type="text" name="roll_no" class="form-control" />
                        </div>
                        <div class="mb-3 col-md-12">
                            <button type="submit" class="btn btn-primary">Submit</button>
                        </div>
                    </div>

                </form>
            </div>
        </div>
    </div>
</div>

@endsection

Define the Routes in routes/web.php

Route::get('students/create', [App\Http\Controllers\StudentController::class, 'create']);
Route::post('students', [App\Http\Controllers\StudentController::class, 'store']);

Add code in controller as follows: 

public function store(Request $request)
{
    $student =  Student::create([
        'name' => $request->name,
        'email' => $request->email,
        'phone' => $request->phone
    ]);

    $student->studentDetail()->create([
        'alternate_phone' => $request->alternate_phone,
        'course' => $request->course,
        'roll_no' => $request->roll_no,
    ]);

    return redirect('students')->with('message','Added Successfully');
}



Method 2: Create or Update "student_details" from another page using the "id" from students_table. 


Store/Insert the Students Data as follows:

public function store(Request $request)
{
    Student::create([
        'name' => $request->name,
        'email' => $request->email,
        'phone' => $request->phone
    ]);
    return redirect('students')->with('message','Added Successfully');
}


Lets Update the data as follows:

Route::put('/students/{student}', 'update');
public function update(Student $student, Request $request)
{
    $student->update([
        'fullname' => $request->fullname,
        'email' => $request->email,
        'phone' => $request->phone,
    ]);

    $student->studentDetail()->update([
        'alter_phone' => $request->alter_phone,
        'course' => $request->course,
        'roll_no' => $request->roll_no,
    ]);

    return redirect('students')->with('message','Student and Student Details Updated');
}


Now, lets Create or Update data in StudentDetails with student_id as follows: 

When it don't have a record of "student id 1", the below code will create/save/insert data into students_details_table.

If the data already exists with specific "student id 1", the below code will update the record. 

public function storeOrUpdateDetails(Request $request, $student_id)
{
    $student = Student::findOrFail($student_id);
    $student->studentDetail()->updateOrCreate(
        [
            'student_id' => $student_id,
        ],
        [
            'alternate_phone' => $request->alternate_phone,
            'course' => $request->course,
            'roll_no' => $request->roll_no,
        ]
    );
    return redirect('students')->with('message','Saved Successfully');
}


Step 4: Lets Display / Read the data using One to One relationship in laravel eloquent:


Method 1: To get data, paste the following code in the Controller:
public function edit($student_id)
{
    $student = Student::findOrFail($student_id)->studentDetail;
    return view('student.edit', compact('student'));
}

now, you can get the details of both tables as follows, in path= resources/views/student/edit.blade.php:

<div class="row">
    <h4>Student Details</h4>
    <div class="mb-3 col-md-4">
        <label>Alternate Phone</label>
        <input type="text" name="alternate_phone" value="{{ $student->alternate_phone }}" class="form-control" />
    </div>
    <div class="mb-3 col-md-4">
        <label>Course</label>
        <input type="text" name="course" value="{{ $student->course }}" class="form-control" />
    </div>
    <div class="mb-3 col-md-4">
        <label>Roll No.</label>
        <input type="text" name="roll_no" value="{{ $student->roll_no }}" class="form-control" />
    </div>
</div>


Method 2: To get data, paste the following code in controller:
public function edit($student_id)
{
    $student = Student::findOrFail($student_id);
    return view('student.edit', compact('student'));
}

now, you get the details from both the table, but the variable $student gets only students_table data. and to get student_details_table data we will use one to one relationship (hasOne() Relationship) in form as follows. 

<div class="row">
    <h4>Student</h4>
    <div class="col-md-4 mb-3">
        <label>Name</label>
        <input type="text" name="name" value="{{ $student->name }}" class="form-control" />
    </div>
    <div class="col-md-4 mb-3">
        <label>Email</label>
        <input type="text" name="email" value="{{ $student->email }}" class="form-control" />
    </div>
    <div class="col-md-4 mb-3">
        <label>Phone</label>
        <input type="text" name="phone" value="{{ $student->phone }}" class="form-control" />
    </div>
</div>
<div class="row">
    <h4>Student Details</h4>
    <div class="mb-3 col-md-4">
        <label>Alternate Phone</label>
        <input type="text" name="alternate_phone" value="{{ $student->studentDetail->alternate_phone }}" class="form-control" />
    </div>
    <div class="mb-3 col-md-4">
        <label>Course</label>
        <input type="text" name="course" value="{{ $student->studentDetail->course }}" class="form-control" />
    </div>
    <div class="mb-3 col-md-4">
        <label>Roll No.</label>
        <input type="text" name="roll_no" value="{{ $student->studentDetail->roll_no }}" class="form-control" />
    </div>
    <div class="mb-3 col-md-12">
        <button type="submit" class="btn btn-primary">Submit</button>
    </div>
</div>


Step 5: Delete data as simple as that:

public function destroy($student_id)
{
    Student::findOrFail($student_id)->delete();
    return redirect('students')->with('message','Daleted Successfully');
}

If you are using resource route:

public function destroy(Student $student)
{
    $student->delete();
    return redirect('students')->with('message','Daleted Successfully');
}


In case of you have not set your foreign key in the migration, so that time you use below code to delete record from both tables data.

public function destroy(Student $student)
{
    $student->studentDetail()->delete();
    $student->delete();
    return redirect('students')->with('message','Daleted Successfully');
}


Thank you.

© Copyright - 2018 - 2022 | All rights reserved at Funda of Web IT