Laravel WhereHas() with Condition
When working with Laravel and you want to fetch data based on a relationship you can limit the results by specifying additional filters for the related model, so how we can do that?
Let's use whereHas()
So let's assume that we have a User Model, and every User belongs to a Country Model, and we want to fetch users that are only from a specified country, to do that you can use the code below:
<?php
namespace App\Http\Controllers;
use Illuminate\Database\Eloquent\Builder;
use App\Models\User;
use Illuminate\Http\Request;
class UserController extends Controller
{
//
public function getUserByCountry(){
$users = User::whereHas('country', function (Builder $query) {
$query->where('name', 'USA');
})->get();
foreach($users as $user){
echo $user->country->name. '<br/>';
}
}
}