I'm working on a Laravel project and I'm trying to set up a one-to-many relationship between two models
How can I create a new user and associate multiple posts with that user using Eloquent?
How do I retrieve all posts belonging to a specific user?
Here's a code of my 'User' and 'Post' models:
// User.php
class User extends Model
{
public function posts()
{
return $this->hasMany(Post::class);
}
}
// Post.php
class Post extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
- I expected to be able to create a new user and associate multiple posts with that user using Eloquent, I anticipated being able to retrieve all posts belonging to a specific user through the established relationship
First, create a table for
post. It should look like this.In migration file
Create a User and post. (if not exist)
In controller
You can use Laravel
factoriesor LaravelTinkerto create dummy data