skip to Main Content

I need to find all results that include this substring (note the leading zero):

$code = '02549';

Nomenclature::where('code', 'like', '%' . $code . '%')->get();

With such a builder, I get the correct request:

select * from `nomenclatures` where `code` like '%02549%'

but if I use a condition in the builder:

Nomenclature::when(true, function($query, $code) {
    $query->where('code', 'like', '%' . $code . '%');
})->get();

then I receive such a request (there is no leading zero):

select * from `nomenclatures` where `code` like '%1%'

Can someone explain what’s going on?

2

Answers


  1. i think your code should be like this:

    Nomenclature::when(true, function($query) use ($code) {
        $query->where('code', 'like', '%' . $code . '%');
    })->get();
    
    Login or Signup to reply.
  2. If you want put $code in the closure as an argument, use this way:

    Nomenclature::when($code, function($query, $code) {
        $query->where('code', 'like', '%' . $code . '%');
    })->get();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search