Cuttlefish
Cuttlefish

Reputation: 187

Laravel: how to add where clause using query builder?

I have this query, made using Laravel query builder:

$rows = DB::table('elements')->where('type', 1);

That corresponds to: "SELECT * from elements WHERE type=1"

Now, in some cases I need to add a second Where to create a query like this:

SELECT * from elements WHERE type=1 AND lang='EN'

Using classic php I'd do something like:

$sql = 'SELECT * from elements WHERE type=1';

if($var==true) $sql .= " AND lang='EN'";

How can I do that using Laravel Query Builder?

Thank you.

Upvotes: 11

Views: 31381

Answers (2)

robert
robert

Reputation: 1

$userId = Auth::id();
$data['user_list'] =DB::table('users')->
select('name')->
where('id','!=',$userId)->
where('is_admin','!=','1')->
get();

like that you use multiple where clause :)

Upvotes: 0

The Alpha
The Alpha

Reputation: 146269

You may try something like this

$query =  DB::table('elements');
$query->where('some_field', 'some_value');

// Conditionally add another where
if($type) $query->where('type', 1);

// Conditionally add another where
if($lang) $query->where('lang', 'EN');

$rows = $query->get();

Also, check this answer.

Upvotes: 36

Related Questions