How to use One to Many Eloquent Relationship in LARAVEL 10

Spread the love

Hello Guys

Explore a Laravel 10 One-to-Many Eloquent Relationship Example

Discover a real-world example of a Laravel 10 One to Many Eloquent Relationship in this tutorial. We’ll delve into a practical Laravel 10 HasMany Relationship Example to provide you with insights into managing multiple relationships in your Laravel project. We’ll also share a step-by-step guide on implementing the Laravel 10 one-to-many sync feature.

In this comprehensive tutorial, you’ll master the art of setting up migrations for one-to-many relationships, including the use of foreign key schemas and synchronization with pivot tables. Learn how to effortlessly create, retrieve, edit, and delete records while delving into the intricacies of one-to-many relationships.

For our example, we’ll create “posts” and “comments” tables, seamlessly connecting them to illustrate the power of Laravel Eloquent Models in establishing one-to-many relationships. Before you dive into record creation, we’ll guide you through database migration and model setup. You can also find a clear depiction of the database table structure below for reference.

Unlock the potential of Laravel 10 for one-to-many relationships and elevate your project’s efficiency.

One to Many Eloquent Relationship will use “hasMany()” and “belongsTo()” for relation.

Create Migrations:

In order to optimize your database structure, it’s essential to initiate the migration process for both posts and comments tables. In conjunction with this operation, a foreign key will be incorporated into the posts table. Let’s proceed with this essential step:

Also Read: How to Create a Custom Error Page in Laravel 10?

posts table migration:
<?php
  
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
  
return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up(): void
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string("name");
            $table->timestamps();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down(): void
    {
        Schema::dropIfExists('posts');
    }
};
comments table migration:
<?php
  
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
  
return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up(): void
    {
        Schema::create('comments', function (Blueprint $table) {
            $table->id();
            $table->foreignId('post_id')->constrained('posts');
            $table->string("comment");
            $table->timestamps();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down(): void
    {
        Schema::dropIfExists('comments');
    }
};

Create Models:

In this tutorial, we’ll create a table model for managing posts and comments efficiently. Additionally, we’ll harness the power of “hasMany()” and “belongsTo()” relationships to establish seamless connections between these two essential models.

Also Read: How to Get the Current URL in Laravel 10?

app/Models/Post.php
<?php
  
namespace App\Models;
  
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
  
class Post extends Model
{
    use HasFactory;
 
    /**
     * Get the comments for the blog post.
     *   
     * Syntax: return $this->hasMany(Comment::class, 'foreign_key', 'local_key');
     *
     * Example: return $this->hasMany(Comment::class, 'post_id', 'id');
     * 
     */
    public function comments(): HasMany
    {
        return $this->hasMany(Comment::class);
    }
}
app/Models/Comment.php
<?php
  
namespace App\Models;
  
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
  
class Comment extends Model
{
    use HasFactory;
  
    /**
     * Get the post that owns the comment.
     *  
     * Syntax: return $this->belongsTo(Post::class, 'foreign_key', 'owner_key');
     *
     * Example: return $this->belongsTo(Post::class, 'post_id', 'id');
     * 
     */
    public function post(): BelongsTo
    {
        return $this->belongsTo(Post::class);
    }
}

Retrieve Records:

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\Post;
  
class PostController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        $comments = Post::find(1)->comments;
  
        dd($comments);
    }
}

Also Read: How to Get the Last Inserted Id in Laravel 10?

<?php
 
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\Comment;
  
class PostController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        $post = Comment::find(1)->post;
  
        dd($post);
    }
}

Create Records:

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\Post;
use App\Models\Comment;
  
class PostController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        $post = Post::find(1);
   
        $comment = new Comment;
        $comment->comment = "Hi itcodestuff.com";
           
        $post = $post->comments()->save($comment);
    }
}

Also Read: How to Resize Images Before Upload in LARAVEL 10

<?php
  
namespace App\Http\Controllers;
   
use Illuminate\Http\Request;
use App\Models\Post;
use App\Models\Comment;
  
class PostController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        $post = Post::find(1);
   
        $comment1 = new Comment;
        $comment1->comment = "Hi itcodestuff.com Comment 1";
           
        $comment2 = new Comment;
        $comment2->comment = "Hi itcodestuff.com Comment 2";
           
        $post = $post->comments()->saveMany([$comment1, $comment2]);
    }
}

Also Read: How to Generate Barcode using Laravel 10 with example

<?php
   
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\Post;
use App\Models\Comment;
  
class PostController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        $comment = Comment::find(1);
        $post = Post::find(2);
           
        $comment->post()->associate($post)->save();
    }
}

Dive into our collection of Laravel blogs – your go-to source for expert insights.

Leave a Comment