Eloquent Has One of Many Tutorial in Laravel 11

 <?php


namespace App\Http\Controllers;

use App\Models\Customer;
use Illuminate\Http\Request;

class CustomerController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        // showing All customers details from "customers" table
        // $customers = Customer::get();
        // return $customers;

        // showing All customers details with their latest Orders
        // $customers = Customer::with("latestOrder")->get();
        // return $customers;

        // showing Any particular customers details
        // $customers = Customer::with("latestOrder")->find(2);
        // return $customers;

        // showing the oldest order of customer number 2 as shown below :
        // $customers = Customer::with("oldestOrder")->find(2);
        // return $customers;

        // showing the oldest order of customer number 1 as shown below :
        // $customers = Customer::with("oldestOrder")->find(1);
        // return $customers;

        // showing largest amount of customer number 1 as shown below :
        // $customers = Customer::with("largestOrder")->find(1);
        // return $customers;

        // showing smallest amount of customer number 1 as shown below :
        // $customers = Customer::with("smallestOrder")->find(1);
        // return $customers;

        // showing All largest amount of all customers as shown below :
        // $customers = Customer::with("largestOrder")->get();
        // return $customers;

        // showing All smallest amount of all customers as shown below :
        // $customers = Customer::with("smallestOrder")->get();
        // return $customers;

        // showing all customers with their all orders from "orders" table
        // $customers = Customer::with("orders")->get();
        // return $customers;

        // showing all customers with their largest orders from "orders" table
        // $customers = Customer::with("orders")->with("largestOrder")->get();
        // return $customers;

        // showing all customers with their smallest orders from "orders" table
        // $customers = Customer::with("orders")->with("smallestOrder")->get();
        // return $customers;

        // showing all customers with their latest orders from "orders" table
        // $customers = Customer::with("orders")->with("latestOrder")->get();
        // return $customers;

        // showing all customers with their oldest orders from "orders" table
        $customers = Customer::with("orders")->with("oldestOrder")->get();
        return $customers;
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * 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\CustomerController File




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

namespace App\Http\Controllers;

use App\Models\Order;
use Illuminate\Http\Request;

class OrderController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $order = Order::create([
            "amount" => 2300.00,
            "customer_id" => 2
        ]);
    }

    /**
     * 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)
    {
        //
    }
}





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

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Customer extends Model
{
    public $timestamps = false;
    protected $table = "customers";
    protected $fillable = ["name", "email", "phone"];

    public function orders()
    {
        return $this->hasMany(Order::class);
    }

    public function latestOrder()
    {
        // Here from "Many" table, only one record will fetch because we have used "hasOne()" method
        return $this->hasOne(Order::class)->latestOfMany();
    }

    public function oldestOrder()
    {
        return $this->hasOne(Order::class)->oldestOfMany();
    }

    // Below "max" and "min" are aggregate methods
    public function largestOrder()
    {
        return $this->hasOne(Order::class)->ofMany("amount", "max");
    }

    public function smallestOrder()
    {
        return $this->hasOne(Order::class)->ofMany("amount", "min");
    }
}





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

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    public $timestamps = true;
    protected $table = "orders";
    protected $fillable = ["amount", "customer_id"];
}





Below File is database\json\customers File
[
    {
        "name": "Yahoo Baba",
        "email": "yahoobaba@gmail.com",
        "phone": "99887744"
    },
    {
        "name": "Salman Khan",
        "email": "salman@gmail.com",
        "phone": "88447755"
    },
    {
        "name": "Deepika Padukone",
        "email": "deepika@gmail.com",
        "phone": "77663322"
    },
    {
        "name": "Abhishek Bachchan",
        "email": "abhishek@gmail.com",
        "phone": "55667788"
    }
]




Below File is database\json\orders File
[
    {
        "amount": 2500.00,
        "customer_id": 2
    },
    {
        "amount": 3600.00,
        "customer_id": 1
    },
    {
        "amount": 5400.00,
        "customer_id": 3
    },
    {
        "amount": 5684.00,
        "customer_id": 2
    },
    {
        "amount": 2453.00,
        "customer_id": 4
    },
    {
        "amount": 1456.00,
        "customer_id": 3
    },
    {
        "amount": 2877.00,
        "customer_id": 1
    },
    {
        "amount": 1233.00,
        "customer_id": 2
    },
    {
        "amount": 1478.00,
        "customer_id": 3
    },
    {
        "amount": 9874.00,
        "customer_id": 1
    }
]





Below File is database\migrations\2024_12_11_124611_create_customers_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('customers', function (Blueprint $table) {
            $table->id();
            $table->string("name");
            $table->string("email", 50)->unique();
            $table->string("phone", 50)->unique();
        });
    }

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





Below File is database\migrations\2024_12_12_043320_create_orders_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('orders', function (Blueprint $table) {
            $table->id();
            $table->decimal("amount", 9, 2);
            $table->unsignedBigInteger("customer_id");
            $table->foreign("customer_id")->references("id")->on("customers")->onUpdate("cascade")->onDelete("cascade");
            $table->timestamps();

            // Second way for making Foreign key as shown below :
            // $table->foreignId("customer_id")->constrained("customers")->onUpdate("cascade")->onDelete("cascade");
        });
    }

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





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

namespace Database\Seeders;

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

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

        $customers->each(function ($customer) {
            Customer::create([
                "name" => $customer->name,
                "email" => $customer->email,
                "phone" => $customer->phone
            ]);
        });
    }
}





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

namespace Database\Seeders;

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

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

        $orders->each(function ($order) {
            Order::create([
                "amount" => $order->amount,
                "customer_id" => $order->customer_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([
            CustomerSeeder::class,
            OrderSeeder::class
        ]);
    }
}





Below File is routes\web File
<?php

use App\Http\Controllers\CustomerController;
use App\Http\Controllers\OrderController;
use Illuminate\Support\Facades\Route;

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

Route::resource("customer", CustomerController::class);

Route::resource("order", OrderController::class);









Comments

Popular posts from this blog

Eloquent Many to Many Relationship Tutorial in Laravel 11

Eloquent with JSON Data Columns Tutorial in Laravel 11

Blade Template Tutorial Three Template Inheritance in Laravel 11