PHP

Define One-to-Many Eloquent Relationships

Learn how to define and interact with one-to-many relationships between models in Laravel Eloquent, enabling structured data access and management.

// In app/Models/User.php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    public function posts()
    {
        return $this->hasMany(Post::class);
    }
}

// In app/Models/Post.php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

// Example Usage
$user = User::find(1);
foreach ($user->posts as $post) {
    echo $post->title . "
";
}

$post = Post::find(1);
echo $post->user->name . "
";
How it works: This snippet demonstrates how to set up a one-to-many relationship between `User` and `Post` models. The `User` model uses `hasMany` to indicate it can have many posts, while the `Post` model uses `belongsTo` to indicate it belongs to a single user. This allows you to easily access related models using dynamic properties, like `$user->posts` or `$post->user`, providing an intuitive way to navigate your database relationships.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs