Ask Your Question

Revision history [back]

In Laravel, we can use variables in relationships by passing them as parameters to the relationship method.

For example, let's say we have a User model and a Post model. The User model has many posts, but we want to retrieve only the posts created by a specific user. We can pass the user_id variable to the posts relationship like this:

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

In this example, we're using the where method to filter the posts by the userid of the current user. We're also using the $this->id variable to retrieve the userid value from the User model.

To use this relationship in our code, we can simply call the posts() method on a User instance:

$user = User::find(1);
$posts = $user->posts;

This will return a collection containing only the posts created by the user with the ID of 1.