PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, March 7, 2022

[FIXED] Where clauses and search

 March 07, 2022     laravel, search, where-clause     No comments   

Issue

I'm new in Laravel and Livewire. I have problem with my code, I'm trying to use where clauses and search in one query. I have code like this.

This is in my controller

public function read()
{
    return Groom::query()
        ->search($this->search)
        ->orderBy($this->sortBy, $this->sortDirection)
        ->paginate($this->perPage);
}

and this one in my model

public function scopeSearch($query, $val)
{
    return $query
        ->where('status', '<>', 'selesai')
        ->leftJoin('pets', 'pets.id', '=', 'grooms.pet_id')
        ->where('name', 'like', '%' .$val. '%')
        ->where(function ($query) use ($val) {
            $query
                ->Orwhere('service', 'like', '%'. $val. '%')
                ->Orwhere('address', 'like', '%' .$val. '%')
                ->Orwhere('status', 'like', '%' .$val. '%');
        });
}

There's no error there, but my search isn't working


Solution

Your generated SQL query is

select * from grooms
left join "pets" on "pets"."id" = "grooms"."pet_id"
where "status" <> 'selesai'
and "name" like ? and (
    "service" like ?
    or "address" like ?
    or "status" like ?
)
order by ...

Perhaps you want the name filter to be inside that grouped where? Try

public function scopeSearch($query, $val)
{
    return $query
        ->where('status', '<>', 'selesai')
        ->leftJoin('pets', 'pets.id', '=', 'grooms.pet_id')
        ->where(function ($query) use ($val) {
            $query
                ->orWhere('name', 'like', '%' .$val. '%')
                ->orwhere('service', 'like', '%'. $val. '%')
                ->orwhere('address', 'like', '%' .$val. '%')
                ->orwhere('status', 'like', '%' .$val. '%');
        });
}


Answered By - IGP
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing