Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

deepu07's avatar
Level 11

Laravel Query builder IfElse

Hey folks, Can anyone help me that how to apply if else condition in query builder? for example if my status =1 i want to execute one cond and status !=1 execute other cond. Any help that would be appreciated. Thanks in advance. Here is my query

`//Query Builder

        $this->db->select('id, status, new_class')
        ->from('table1 a')
        ->join('table2 b', 'b.id = a.number')
        ->join('table3 c', 'c.class = a.new_class')
        ->where('c.id', $inputId);

Here if status = 1 i want to stop execution here if status is in [2,3,4] i wanna execute below code too. How can I achieve in laravel query builder.

        ->where_in('status', [ 2, 3, 4 ])
        ->where('b.admin', true)
        ->where('b.teacher', true);
    $results = $this->db->get()->result();
0 likes
1 reply
jlrdw's avatar

Just quick pseudocode

$query = whatever

If some condition

$query = $query . Your added criteria

Else

$query = $query . Maybe some other criteria

$results = $query-> get or paginate here

Please or to participate in this conversation.