Home > front end >  I am running a eloquent query, but i am stuck in a position
I am running a eloquent query, but i am stuck in a position

Time:12-11

I am new in Laravel. $year 'all' is every possible year

all, 2022, 2021, 2020, 2019

if i pass params any of them except all its working fine. but when i pass all as condition. i have no idea what to do? Please help me.

public function findResultServiceFeeDubai($address, $type, $year, $norows){
     
        $result = DB::table('service-charges')
        ->select('address', 'year', 'type', 'total_charge_sqft')
        ->orWhere('address', 'LIKE', "%".$address."%")
        ->where('type', $type)
        ->where('year', $year)
        ->limit($norows)
        ->get();
        $response = $result;
        return response()->json($response, 200);

    }
Route::get('/findResultServiceFeeDubai/{name}/{type}/{year}/{norows}',[UserController::class,'findResultServiceFeeDubai'])->name('findResultServiceFeeDubai');

CodePudding user response:

You are calling methods on a Query Builder. It is an object so you can assign it to a variable and make calls to it as needed to build your query. The get call is what is actually executing the query and returning a result. If you want to conditionally add query conditions to that query you can just use if statements (if you prefer to not use the functional approach):

$query = DB::table('service-charges')
    ->select('address', 'year', 'type', 'total_charge_sqft')
    ->where('address', 'LIKE', '%'. $address .'%')
    ->limit($norows);

if ($year !== 'all') {
    $query->where('year', $year);
}

if ($type !== 'all') {
    $query->where('type', $type);
}

$result = $query->get();
  • Related