Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

fadahye's avatar

No query results for model Livewire

I have this code which is working but i have to set default value for $region_id and $distrcit_id which is nt what i want. my intention is anyone can search project by one or more of these fields if you know better way please help thanks. and this is using livewire with laravel

public $state_id;
 public $type_id;
    public $region_id=1;
    public $district_id=1;

i would like to be able to set empty without getting No query results for model
    public $region_id;
    public $district_id1;
  	
$r= Region::findOrfail($this->region_id);
$d=District::findOrfail($this->district_id);
       
    
            
  $searchprojects = Project::where('state_id', $this->state_id)
                                ->where('type_id', $this->type_id)
            ->whereHas('regions', function($q) use ($r){
                        $q->whereIn('region_id', $r);})
            ->WhereHas('districts',function ($q) use ($d){
                        $q->whereIn('district_id', $d );})->get();
0 likes
3 replies
Snapey's avatar
Snapey
Best Answer
Level 122

break down your query and use if to include sections of your query if region and district is set

$query = Project::where('state_id', $this->state_id)
    ->where('type_id', $this->type_id);

if($this->region_id) {
    $query->whereHas('regions', function($q) {
        $q->whereIn('region_id', $this->region_id);
    });
}

if($this->district_id) {
    $query->WhereHas('districts',function ($q){
        $q->whereIn('district_id', $this->district_id);
    });
}

$searchprojects = $query->get();
2 likes

Please or to participate in this conversation.