Laravel - Relationships - Querying Relations
Since all Eloquent relationships are defined via methods, you may call those methods to obtain an instance of the relationship without actually executing a query to load the related models. In addition, all types of Eloquent relationships also serve as query builders, allowing you to continue to chain constraints onto the relationship query before finally executing the SQL query against your database.
For example, imagine a blog application in which a
User model has many associated
hasMany(Post::class); } }
You may query the
posts relationship and add additional constraints to the relationship like so:
use App\Models\User; $user = User::find(1); $user->posts()->where('active', 1)->get();
You are able to use any of the Laravel query builder's methods on the relationship, so be sure to explore the query builder documentation to learn about all of the methods that are available to you.