upskilling is the key to moving forward

Upskilling Is The Key To Moving Forward

September 21, 2020
get started with bitbucket piplines: a simple php composer pipeline

Get Started With Bitbucket Pipelines: A Simple PHP Composer Pipeline

October 16, 2020

Laravel Eloquent: Advanced Queries On Relationships Using whereHas

September 28, 2020 / Hristo Mitev

Eloquent is amazing, and 90% of queries can be dealt with using where, find, has, etc. But sometimes we need to query a relationship itself. E.g.

Let’s say we have the following Models: Car, Garage, Owner.

An Owner can have many Garages, but a Garage can only have one Owner.
A Garage can have many Cars, but a Car can only belong to one Garage.

Since a car belongs to a garage, and a garage belongs to an owner, we can query a cars owner using Eloquents’

hasOneThrough method.

But since an owner can have many garages, how can we easily get all of their cars? This is where the power of whereHas comes in.

This will return all cars that belong to a garage owned by the owner that $owner_id matches with.

Share

Hristo Mitev

Hristo is a frontend developer with knowledge and experience in Laravel.

Laravel Eloquent: Advanced Queries On Relationships Using whereHas
This website uses cookies to improve your experience. By using this website you agree to our Data Protection Policy.
Read more