Laravel: how to add where clause using query builder?
Asked Answered
U

2

11

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.

Urania answered 24/11, 2013 at 19:54 Comment(0)
H
36

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.

Hydrochloride answered 24/11, 2013 at 20:33 Comment(3)
They could also be chained: $query->where('some_field', 'some_value')->where('type', 1);Anent
@ManuelPedrera, Yes, but to add where conditionally, you cant chain, because OP is about to check a condition before (s)he adds another where clause.Hydrochloride
@RCV Yes, that's why I posted a comment to expand, and not another answer.Anent
P
0
$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 :)

Pentarchy answered 3/7, 2017 at 10:30 Comment(1)
Welcome to Stack Overflow! Thank you for this code snippet, which may provide some immediate help. A proper explanation would greatly improve its educational value by showing why this is a good solution to the problem, and would make it more useful to future readers with similar, but not identical, questions. Please edit your answer to add explanation, and give an indication of what limitations and assumptions apply.Erythrite

© 2022 - 2024 — McMap. All rights reserved.