Eloquent One To Many Relationships Tutorial in Laravel 11

 <?php


namespace App\Http\Controllers;

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

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

        // $users = User::with("post")->get();
        // return $users;

        // $users = User::with("post")->find(2);    //First Way
        // $users = User::find(2);     //Second Way
        // $posts = $users->post;
        // return $users;

        // Those users who have not any post as shown below :
        // $users = User::doesntHave("post")->get();
        // return $users;

        // Those users names only who have post as shown below :
        // $users = User::has("post")->get();
        // return $users;

        // Those users names with post who have post as shown below :
        // $users = User::has("post")->with("post")->get();
        // return $users;

        // Those users names with post who have 3 or more than 3 post as shown below :
        // $users = User::has("post",">=",3)->with("post")->get();
        // return $users;

        // users names with number of post with "withCount()" method as shown below :
        // $users = User::withCount("post")->get();
        // return $users;

        // users details with some specific columns as shown below :
        $users = User::select(["name", "email"])->withCount("post")->get();
        return $users;
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        // Method 1 : Insert data in "posts" table as shown below :
        // $post = new Post([
        //     "title" => "News Title - Test",
        //     "description" => "Just Testing...."
        // ]);

        // $user = User::find(2);

        // $user->post()->save($post);

        // Insert data Method 2 :
        // $user = User::find(2);

        // $user->post()->create([
        //     "title" => "News Title 2 - Test",
        //     "description" => "Just Testing 2 ...."
        // ]);

        // Insert Multiple data in database Method 3 :
        $user = User::find(4);
        $user->post()->createMany([
            [
                "title" => "News Title 3 - Test",
                "description" => "Just Testing 3 ...."
            ],
            [
                "title" => "News Title 4 - Test",
                "description" => "Just Testing 4 ...."
            ]
        ]);
    }

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





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

namespace App\Http\Controllers;

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

class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        // $posts = Post::get();
        // return $posts;

        // $posts = Post::with("user")->get();
        // return $posts;

        // To find particuar user information we can use find() method as shown below :
        // $posts = Post::with("user")->find(2);
        // return $posts;

        // echo $posts->title . "<br>";
        // echo $posts->description . "<br>";
        // echo $posts->user->name;

        // All "posts" table data will show in table as shown below :
        // $posts = Post::with("user")->get();
        // foreach($posts as $data) {
        //     echo "<div style='border:1px solid red;margin:0 0 10px'>
        //             <h3>$data->title</h3>
        //             <span>{$data->user->name}</span>
        //             <p>$data->description</p>
        //     </div>";
        // }

        // $posts = Post::with("user")->where("title","News Title Two")->get();
        // return $posts;

        // When we want to search in another table at that time we have to use withWhereHas() method
        // $posts = Post::withWhereHas("user",function($query){
        //     $query->where("name","Salman Khan");
        // })->get();
        // return $posts;

        // If we want to seach for multiple user in another table as shown below :
        // $posts = Post::withWhereHas("user",function($query){
        //     $query->where("name","Salman Khan")->orWhere("name","Deepika Padukone");
        // })->get();
        // return $posts;

        $users = User::where("name", "Salman Khan")->get();
        $posts = Post::whereBelongsTo($users)->get();
        return $posts;
    }

    /**
     * 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\User File
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    public $timestamps = false;
    // protected $guarded = [];    //First way
    protected $fillable = ["name", "email"];    //Second way

    public function post()
    {
        return $this->hasMany(Post::class);
    }
}





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

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    // protected $guarded = [];  //First way
    protected $fillable = ["title", "description", "user_id"];    //Second way both are same
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}





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




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





Below File is database\migrations\2024_12_10_072517_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();
        });
    }

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





Below File is database\migrations\2024_12_10_072614_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", 50);
            $table->longText("description");
            $table->foreignId("user_id")->constrained("users")->onUpdate("cascade")->onDelete("cascade");
            $table->timestamps();
        });
    }

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





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
            ]);
        });
    }
}





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





Below File is routes\web File
<?php

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

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

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