PHP
Defining One-to-Many Eloquent Relationships
Learn to establish one-to-many relationships between Laravel Eloquent models, enabling seamless retrieval of related data and structured database interactions.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class User extends Model
{
/**
* Get the posts for the user.
*/
public function posts(): HasMany
{
return $this->hasMany(Post::class);
}
}
class Post extends Model
{
/**
* Get the user that owns the post.
*/
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
}
// Usage example:
$user = User::find(1);
foreach ($user->posts as $post) {
echo $post->title . "
";
}
$post = Post::find(5);
echo $post->user->name . "
";
How it works: This code illustrates how to define a one-to-many relationship between two Eloquent models, `User` and `Post`. In the `User` model, the `posts()` method uses `hasMany()` to indicate that a user can have multiple posts. In the `Post` model, the `user()` method uses `belongsTo()` to signify that a post belongs to a single user. Laravel automatically infers the foreign key (e.g., `user_id` on the `posts` table) but you can pass additional arguments to customize this. Once defined, you can access related models as properties, enabling intuitive navigation through your database relationships.