php - Laravel Problem: Please check why this code behave like this?

$sallery_min = 4000;
$sallery_max = 30000;

$job = Job::where('status', 1);
      
if ($sallery_min && $sallery_max) {
    $job->whereIn('salary_level', $sallery_level);
}
      
$data = $job->orderBy('id', 'desc')->get();
dd($data);

when use above mention code then i got 7 result its working fine. But when i change in this code like this then 11 result come from database.can i do not do code like this. what happen when Job::where('status', 1); change into $job = new Job(); $job->where('status', 1);. why result come diffrent

$sallery_min = 4000;
$sallery_max = 30000;

$job = new Job();
$job->where('status', 1);
      
if ($sallery_min && $sallery_max) {
    $job->whereIn('salary_level', $sallery_level);
}
         
$data=$job->orderBy('id', 'desc')->get();
dd($data);

Answer

Solution:

in your code you are getting the result where status is 1 1 from your database by using this query

$job = Job::where('status', 1);

but you are not retriving the objects because you dont use get() or first().WHer first() is use for retrieving single row and get() is use for multipe row. So for retrieving teh expected result you have to use get() method like this.

$jobs = Job::where('status', 1)->get();

Answer

Solution:

If you want to query the database with a new Job object, you should use the method chaining, like:

$job = new Job();

$jobs = $job->where('status', 1)
        ->when($sallery_min && $sallery_max, function ($q) use ($sallery_min, $sallery_max) { 
            return $q->whereBetween('salary_level', [$sallery_min, $sallery_max]);
        })->get();

dd($jobs);
    

However, Eloquent provides the static method for convenience. Use it unless you have a specific reason to stick on with the new Object word around.

Extra Note: The above code uses Conditional Where Clauses which avoids if ... else ... statements.

Source