Laravel: Eloquent - One to Many Relationship
Carlos Costa
One-to-Many relationship is the most common relationship in Laravel. This relationship is used when a model has multiple instances of another model.
Let’s say we have a User
model and a Post
model. A User
can have multiple Post
s, but a Post
can only have one User
.
In this node we will create migrations, models, factories and test to demonstrate how to create a One to Many relation.
Let’s start by creating our files:
php artisan make:model Post -mf --pest
Migrations
Ok, let’s define migrations for our models:
//posts
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->string('title');
$table->text('body');
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('posts')->onDelete('cascade');
});
Models
And the relations in our models:
//post
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
public function user()
{
return $this->belongsTo(User::class);
}
}
Factories
And factories for our models:
//post
class PostFactory extends Factory
{
public function definition(): array
{
return [
'title' => fake()->sentence(),
'body' => fake()->paragraph(),
'user_id' => User::factory(),
];
}
}
Tests
To finally, let’s create a test to check if our relation is working:
use App\Models\Post;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
test('Post relationship with User', function () {
$user = User::factory()
->has(Post::factory()->count(3))
->create();
$this->assertCount(3, $user->posts);
foreach ($user->posts as $post) {
$this->assertInstanceOf(Post::class, $post);
}
$firstPost = $user->posts->first();
$this->assertEquals($firstPost->user->id, $user->id);
});