Eloquent One To One Relationships Tutorial in Laravel 11

 <?php


namespace App\Http\Controllers;

use App\Models\Student;
use App\Models\Contact;
use Illuminate\Http\Request;

class StudentController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        // $students = Student::with("contact")->get();
        // $students = Student::with("contact")->find(3);  //Fetch particular record from database
        // return $students;

        // $students = Student::with("contact")->find(3);
        // echo $students->name . "<br>";  //Printing particular column name value
        // echo $students->contact->email . "<br>";

        // Fetching particular condition records from "students" table
        // $students = Student::with("contact")->where("gender","F")->get();
        // return $students;

        // Fetching particular condition records from "contacts" table
        // $students = Student::withWhereHas("contact", function($query){
        //     $query->where("city","Delhi");
        // })->get();
        // return $students;

        // Fetching particular records with condition in both tables "students" and "contacts"
        // Here below "withWhereHas()" method is used
        // For example: if we want to search records with gender Male from "students" table and with city Delhi from "contacts" table as shown below :
        // $students = Student::where("gender","M")->withWhereHas("contact",function($query){
        //     $query->where("city","Delhi");
        // })->get();
        // return $students;

        // Below code shows result from only "students" table, Not from "contacts" table
        // Here below "whereHas()" method is used when both tables have one-to-one relationship as shown below
        // sometimes we have condition like we want to match records from both tables and fetch records from only one table as shown below :
        $students = Student::where("gender", "M")->whereHas("contact", function ($query) {
            $query->where("city", "Delhi");
        })->get();
        return $students;
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        // we can add record in both tables simultaneously from one controller using one-to-one relationship as shown below :
        $student = Student::create([
            "name" => "John Abraham",
            "age" => 18,
            "gender" => "M"
        ]);

        $student->contact()->create([
            "email" => "john@gmail.com",
            "phone" => "9988776634",
            "address" => "#456 JA Road",
            "city" => "Mumbai"
        ]);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
    }
}
Above File is app\Http\Controllers\StudentController File





Below File is app\Http\Controllers\ContactController File
<?php

namespace App\Http\Controllers;

use App\Models\Contact;
use App\Models\Student;
use Illuminate\Http\Request;

class ContactController extends Controller
{
    public function show()
    {
        $contacts = Contact::with("student")->get();
        return $contacts;
    }
}






Below File is app\Models\Student File
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Student extends Model
{
    public $timestamps = false;
    protected $fillable = ["name", "age", "gender"];

    public function contact()
    {
        return $this->hasOne(Contact::class);
    }
}





Below File is app\Models\Contact File
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{
    public $timestamps = false;
    protected $fillable = ["email", "phone", "address", "city", "student_id"];

    public function student()
    {
        // When we want to attach Foreign key table to Primary key table at that time we have to use belongsTo() method
        // To make Inverse relationship, we have to use belongsTo() method as shown below :
        // When we wan to make straight relationship(when another table has Foreign key) at that time we have to use hasOne() method
        return $this->belongsTo(Student::class);
    }
}





Below File is database\json\students.json File
[
    {
        "name": "Yahoo Baba",
        "age": 20,
        "gender": "M"
    },
    {
        "name": "Salman Khan",
        "age": 22,
        "gender": "M"
    },
    {
        "name": "Akshay Kumar",
        "age": 23,
        "gender": "M"
    },
    {
        "name": "Kirti",
        "age": 20,
        "gender": "F"
    },
    {
        "name": "Deepika",
        "age": 20,
        "gender": "F"
    }
]





Below File is database\json\contacts.json File
[
    {
        "email": "yahoobaba@gmail.com",
        "phone": "123456789",
        "address": "#123 YB Road",
        "city": "Chandigarh",
        "student_id": 1
    },
    {
        "email": "salman@gmail.com",
        "phone": "3344556677",
        "address": "#345, SK Road",
        "city": "Mumbai",
        "student_id": 2
    },
    {
        "email": "akshay@gmail.com",
        "phone": "8855226611",
        "address": "#456, AK Road",
        "city": "Delhi",
        "student_id": 3
    },
    {
        "email": "kirti@gmail.com",
        "phone": "99887744225",
        "address": "#678, KS Road",
        "city": "Delhi",
        "student_id": 4
    },
    {
        "email": "deepika@gmail.com",
        "phone": "7788554411",
        "address": "#321, DP Road",
        "city": "Bangaluru",
        "student_id": 5
    }
]





Below File is database\migrations\2024_12_09_091952_create_students_table File
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('students', function (Blueprint $table) {
            $table->id();
            $table->string("name");
            $table->integer("age");
            $table->string("gender");
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('students');
    }
};





Below File is database\migrations\2024_12_09_092032_create_contacts_table File
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('contacts', function (Blueprint $table) {
            $table->id();
            $table->string("email");
            $table->string("phone");
            $table->string("address");
            $table->string("city");
            $table->integer("student_id");
            $table->foreign("student_id")->references("id")->on("students")->onDelete("cascade")->onUpdate("cascade");
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('contacts');
    }
};





Below File is database\seeders\StudentSeeder File
<?php

namespace Database\Seeders;

use App\Models\Student;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\File;

class StudentSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $json = File::get(path: "database/json/students.json");
        $students = collect(json_decode($json));

        $students->each(function ($student) {
            Student::create([
                "name" => $student->name,
                "age" => $student->age,
                "gender" => $student->gender
            ]);
        });
    }
}





Below File is database\seeders\ContactSeeder File
<?php

namespace Database\Seeders;

use App\Models\Contact;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\File;

class ContactSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $json = File::get(path: "database/json/contacts.json");
        $contacts = collect(json_decode($json));

        $contacts->each(function ($contact) {
            Contact::create([
                "email" => $contact->email,
                "phone" => $contact->phone,
                "address" => $contact->address,
                "city" => $contact->city,
                "student_id" => $contact->student_id
            ]);
        });
    }
}





Below File is database\seeders\DatabaseSeeder File
<?php

namespace Database\Seeders;

use App\Models\User;
// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     */
    public function run(): void
    {
        // User::factory(10)->create();

        // User::factory()->create([
        //     'name' => 'Test User',
        //     'email' => 'test@example.com',
        // ]);

        $this->call([
            StudentSeeder::class,
            ContactSeeder::class
        ]);
    }
}





Below File is routes\web File
<?php

use App\Http\Controllers\ContactController;
use App\Http\Controllers\StudentController;
use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    return view('welcome');
});

Route::resource("student", StudentController::class);

Route::get("/contact", [ContactController::class, "show"]);







Comments

Popular posts from this blog

Eloquent Many to Many Relationship Tutorial in Laravel 11

Blade Template Tutorial Three Template Inheritance in Laravel 11