NiloLeon's avatar

Eloquent Where filter

It is possible to use where condition only when the field is valorized and if no skip where? For example

$model = (this can have a value or null)
Cars::where([
			['model', '=', $model]
		])->get()

I'd like to filter list of cars with specific model only when $model variable is valorized if no extract all cars Thanks a lot

0 likes
4 replies
tykus's avatar

Using conditional constraints, and assuming the $model is a primitive (otherwise what property of $model do you use as the constraining value?)

$model = (this can have a value or null)
Cars::when($model, function ($builder, $model) {
    $builder->where('model', '=', $model);
})->get()
NiloLeon's avatar

@tykus $model is just a variable number or null. Ehm sorry the real eloquent query is more complex :S

        $data_in = request('data_in');
		$data_fin = request('data_fin');
		$bigcust = request('bigcust'); <= this could be a number or null

		$countRifiuti = Refunds::whereHas(
				'claims', function ($query) use($bigcust){
					$query->where([
						['bigcust', '=', $bigcust],
					]);
				},
			)
			->where([
			['status_ref', '>', 1],
			['status_ref', '<', 5],
			['date_status', '>=', $data_in],
			['date_status', '<=', $data_fin]
		])
			->count();

Refunds belongs to Claims and Claims hasMany Refunds. How can i apply what u say? thanks

NiloLeon's avatar

@tykus I think so is correct

		$countRifiuti = Refunds::whereHas(
				'claims', function ($query) use($bigcust){
					$query->when($bigcust, function ($builder, $bigcust) {
						$builder->where('bigcust', '=', $bigcust);
		});
				},
			)
			->where([
			['status_ref', '>', 1],
			['status_ref', '<', 5],
			['date_status', '>=', $data_in],
			['date_status', '<=', $data_fin]
		])
			->count();
tykus's avatar

@NiloLeon you want the whereHas constraint on the claims relation only if the bigcust is truthy, so I would go the other way around:

$countRifiuti = Refunds::when($bigcust, function($builder, $bigcust) {
    $builder->whereHas('claims', fn($query) => $query->where('bigcust', '=', $bigcust));
})->where([
    ['status_ref', '>', 1],
    ['status_ref', '<', 5],
    ['date_status', '>=', $data_in],
    ['date_status', '<=', $data_fin]
])->count();

Please or to participate in this conversation.