Skip to content
Advertisement

How to use where condition in if statement which is already written in codeigniter

I have got a situation where the $user_id parameter is optional and I used to do this in codeigniter in the way written below. But I am not able to figure it out, How can I write this query in laravel’s eloquent and query builder as well. Any help is much appreciated.

function get_user($user_id) { 
    $this->db->select('u.id as user_id, u.name, u.email, u.mobile');
    if($user_id != '') {
        $this->db->where('user_id', $user_id);
    }
    return $this->db->get('users as u')->result();
}

Thanks

Advertisement

Answer

Using Eloquent:

$modalObject = new ModelName::select('id as user_id', 'name', 'email', 'mobile');

if ($user_id) {
    $modalObject = $modalObject->where('user_id', $user_id);
}

return $modalObject->get();

Using Query Builder:

$builder = DB::table('users')->select('id as user_id', 'name', 'email', 'mobile');

if ($user_id) {
    $builder = $builder->where('user_id', $user_id);
}

return $builder->get();

Replace the ModelName with one defined for the table users.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement