How to use condition in query dynamically

$query   = Order::query();
$keyword = $request->query( 'keyword' ) ?? '';
if ( !empty( $request->query( 'keyword' ) ) ) {
	$query->where( 'id', $request->query( 'keyword' ) )->orWhere('company_name', $keyword)->orWhere('job_number', $keyword);
	$meta_title = 'Invoice #: "' . $request->query( 'keyword' );
}
$orders = $query->orderBy( 'id', 'desc' )->paginate( 10 )->withQueryString();

Now above code can be written elegantly using eloquent method when() that is mentioned in this tutorial step by step. What basically when() method serves is the same purpose in writing dynamic query based on query string existence instead of if else block .

Related Posts


Using WhereIn

Updating multiple rows

Using Like

Using orWhere

What is Query Builder?

Using "with" in eloquent query

Getting last inserted id

Selecting last row of a table

Using parameters in find() method

Using local scope in eloquent

Using global scope in eloquent