0%

Build A Condition Based Query In Laravel

Its common to give user an option to filter the data which they wanted when the data amount is huge and normally you may provide different conditions to filter the data. In this article, I will show you how to build a condition based query in Laravel.
Its pretty easy to be done by the query builder.

for example:
you may give user two options to filter the data. one is the status of your order and other is the general search for the different fields.

for the status option ,we can provide a dropdown list and the general search we can provide a input field to the user.

in the livewire component

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public $search = "";
public $filter_status = "";

public function render()
{
$orders = $this->getData();
return view('livewire.orders.orderlist', [
'orders' => $orders,
]);
}

public function getData()
{
$query = DB::table('orders');
if ($this->filter_status != "*") {
$query->where('status', $this->filter_status);
}
if ($this->search != "") {
$query->where('name', 'like', '%' . $this->search . '%');
}
$query->where('user_id', auth()->id());
$query->orderBy('id', 'desc');
return $query->paginate(10);
}
//reset page after update
public function updatingSearch()
{
$this->resetPage();
}
public function updatingFilterStatus()
{
$this->resetPage();
}