How to use whereHas() and with() in laravel 8?
Laravel is very famous and widely used PHP Framework. Nowadays, I am doing development in Laravel along with other RoR and Java projects.
I was working on a Laravel 8 project in which I had to show related records and also by any criteria if related record doesn’t exist then don’t show main any record.
To achieve required results, I used whereHas() and with() eloquent methods. For this, there must be hasMany() and belongTo() method defined in models.
For example, I had two models Customer and Order.
In Customer Model.
public function orders() {
$this->hasMany("Order");
}
In Order Model.
public function customer() {
$this->belongsTo("Cutomer");
}
Then, I created a repository file where I write all queries.
public function fetchCustomerOrders($where) {
$callBack = function ($query) use($where) {
$query->where(“customer_id”, “=”, $where[“customer_id”])
}
$customers = Customer::whereHas(“orders”, $callback)
->with([‘order’ => $callback])->get();
return $customers;
}
To make code clean, I made a where clause function in “$callback” variable, you can also create a separate private function in which you can define all your where clause and then call it in whereHas and with clauses.
I hope this will help.