How to use laravel scope in a relationship?

by haylee.mertz , in category: PHP Frameworks , 4 months ago

How to use laravel scope in a relationship?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by adan , 4 months ago

@haylee.mertz 

In Laravel, you can use scopes to apply conditions to a relationship in your Eloquent models. Scopes allow you to define common query constraints that can be reused throughout your application.


To use a scope in a relationship, you need to define the scope in the related model and then use it in the relationship definition in the primary model.


For example, let's say you have a User model with a posts relationship. You want to apply a scope to only retrieve published posts. Here's how you can do it:

  1. Define the scope in the Post model:
1
2
3
4
5
6
7
class Post extends Model
{
    public function scopePublished($query)
    {
        return $query->where('status', 'published');
    }
}


  1. Use the scope in the relationship definition in the User model:
1
2
3
4
5
6
7
class User extends Model
{
    public function posts()
    {
        return $this->hasMany(Post::class)->published();
    }
}


Now, when you retrieve posts for a user using the posts relationship, only published posts will be returned.


You can also chain multiple scopes in a relationship to further refine the query. For example, if you have a scope recent defined in the Post model that retrieves posts created within the last week, you can use it like this:

1
2
3
4
public function posts()
{
    return $this->hasMany(Post::class)->published()->recent();
}


This will retrieve only published posts that were created within the last week for the user.