Eloquent Has Many Through Tutorial in Laravel 11

 <?php


namespace App\Http\Controllers;

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

class CountryController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        // Id number 1 means India and country_id 1 is assigned to id 1 and 3 in users table and
        // user_id 1 and 3 assigned to id 2,3,4,6,8,10 in posts table so 6 records will shown as shown below :
        // $country = Country::find(1);
        // return $country->posts;

        // $country = Country::find(3);
        // return $country->posts;

        // with country name above records shown as below :
        // $country = Country::with("posts")->find(3);
        // return $country;

        // $country = Country::with("posts")->get();
        // return $country;

        // Along with users name above records shown as below :
        $country = Country::with("users")->with("posts")->find(1);
        return $country;
    }

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





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

namespace App\Http\Controllers;

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

class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        // $users = User::with("posts")->with("country")->get();
        // return $users;

        // show any specific user information as shown below :
        $users = User::with("posts")->with("country")->find(1);
        return $users;
    }

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




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

namespace App\Http\Controllers;

use Illuminate\Http\Request;

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

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





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

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Country extends Model
{
    public $timestamps = false;
    protected $table = "countries";
    protected $fillable = ["name"];

    public function users()
    {
        return $this->hasMany(User::class);
    }
    public function posts()
    {
        return $this->hasManyThrough(Post::class, User::class);
    }
}





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

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    public $timestamps = false;
    protected $table = "users";
    protected $fillable = ["name", "email", "country_id"];

    public function posts()
    {
        return $this->hasMany(Post::class);
    }
    public function country()
    {
        return $this->belongsTo(Country::class);
    }
}





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

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    public $timestamps = true;
    protected $table = "posts";
    protected $fillable = ["title", "description", "user_id"];
}





Below File is database\json\countries File
[
    {
        "name": "India"
    },
    {
        "name": "Pakistan"
    },
    {
        "name": "Bangladesh"
    }
]




Below File is database\json\users File
[
    {
        "name": "Yahoo Baba",
        "email": "yahoobaba@gmail.com",
        "country_id": 1
    },
    {
        "name": "Salman Khan",
        "email": "salman@gmail.com",
        "country_id": 2
    },
    {
        "name": "Deepika Padukone",
        "email": "deepika@gmail.com",
        "country_id": 1
    },
    {
        "name": "Abhishek Bachchan",
        "email": "abhishek@gmail.com",
        "country_id": 3
    },
    {
        "name": "Shahid Kapoor",
        "email": "shahid@gmail.com",
        "country_id": 2
    }
]




Below File is database\json\posts File
[
    {
        "title": "News Title One",
        "description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt",
        "user_id": 2
    },
    {
        "title": "News Title Two",
        "description": "ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip",
        "user_id": 1
    },
    {
        "title": "News Title Three",
        "description": "ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.",
        "user_id": 3
    },
    {
        "title": "News Title Four",
        "description": "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
        "user_id": 1
    },
    {
        "title": "News Title Five",
        "description": "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium",
        "user_id": 2
    },
    {
        "title": "News Title Six",
        "description": "totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.",
        "user_id": 1
    },
    {
        "title": "News Title Seven",
        "description": "Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos",
        "user_id": 4
    },
    {
        "title": "News Title Eight",
        "description": "qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur,",
        "user_id": 3
    },
    {
        "title": "News Title Nine",
        "description": "adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.",
        "user_id": 4
    },
    {
        "title": "News Title Ten",
        "description": "Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur?",
        "user_id": 3
    }
]




Below File is database\migrations\2024_12_12_071214_create_countries_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('countries', function (Blueprint $table) {
            $table->id();
            $table->string("name");
        });
    }

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





Below File is database\migrations\2024_12_12_071714_create_users_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('users', function (Blueprint $table) {
            $table->id();
            $table->string("name");
            $table->string("email", 50)->unique();
            $table->unsignedBigInteger("country_id");
            $table->foreign("country_id")->references("id")->on("countries")->onUpdate("cascade")->onDelete("cascade");

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

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





Below File is database\migrations\2024_12_12_073118_create_posts_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('posts', function (Blueprint $table) {
            $table->id();
            $table->string("title");
            $table->longText("description");
            $table->unsignedBigInteger("user_id");
            $table->foreign("user_id")->references("id")->on("users")->onUpdate("cascade")->onDelete("cascade");
            $table->timestamps();

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

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





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([
            CountrySeeder::class,
            UserSeeder::class,
            PostSeeder::class
        ]);
    }
}





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

namespace Database\Seeders;

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

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

        $countries->each(function ($country) {
            Country::create([
                "name" => $country->name
            ]);
        });
    }
}





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

namespace Database\Seeders;

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

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

        $users->each(function ($user) {
            User::create([
                "name" => $user->name,
                "email" => $user->email,
                "country_id" => $user->country_id
            ]);
        });
    }
}





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

namespace Database\Seeders;

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

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

        $posts->each(function ($post) {
            Post::create([
                "title" => $post->title,
                "description" => $post->description,
                "user_id" => $post->user_id
            ]);
        });
    }
}





Below File is routes\web File
<?php

use App\Http\Controllers\CountryController;
use App\Http\Controllers\PostController;
use App\Http\Controllers\UserController;
use Illuminate\Support\Facades\Route;

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

Route::resource("country", CountryController::class);

Route::resource("user", UserController::class);

Route::resource("post", PostController::class);





Comments

Popular posts from this blog

Eloquent Many to Many Relationship Tutorial in Laravel 11

Blade Template Tutorial Three Template Inheritance in Laravel 11