Laravel 8 Eloquent orWhereHas Condition

public function index()
{
$name = 'California';
$users = User::with('country','state')
->whereHas('country', function ($query) use($name){
$query->where('name', 'like', '%'.$name.'%');
})
->orWhereHas('state', function ($query) use($name){
$query->where('name', 'like', '%'.$name.'%');
})
->get()
->toArray();
}
<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{

protected $fillable = [
'name',
'email',
'password',
];

public function country()
{
return $this->belongsTo(Country::class);
}

public function state()
{
return $this->belongsTo(State::class);
}
}
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Country extends Model
{
use HasFactory;
}
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class State extends Model
{
use HasFactory;
}
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;

class UserController extends Controller
{
public function index()
{
$name = 'California';
$users = User::with('country','state')
->whereHas('country', function ($query) use($name){
$query->where('name', 'like', '%'.$name.'%');
})
->orWhereHas('state', function ($query) use($name){
$query->where('name', 'like', '%'.$name.'%');
})
->get()
->toArray();
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store