murilo's avatar
Level 10

Find Queries Where Between First Letters Start with *

I have a Question , I have a List of names , like this -

Alexander , Callum , Charles , Charlie , Charlie , Connor , Damian , Daniel , David , Ethan , George , Harry , Jack , Jake , James , James , James , Joe , John , Joseph , Kyle , Liam , Mason , Michael , Noah , Oliver , Oscar , Reece , Rhys , Richard , Robert , Thomas , Thomas , William 

and I want to GET all names between Letters -> A to D , need to show me this -

Alexander , Callum , Charles , Charlie , Charlie , Connor , Damian , Daniel , David 

How could I do it ?

something like this ->

     $query = User::select(['id', 'names' ]->whereBetween('name' , [ 'a%',  '%d'])   ->latest()->get();

Thanks

0 likes
7 replies
Cronix's avatar
Cronix
Best Answer
Level 67
User::select(['id', 'names'])
    ->where('names', 'like', "a%")
    ->orWhere('names', 'like', "b%")
    ->orWhere('names', 'like', "c%")
    ->orWhere('names', 'like', "d%")
    ->orderBy('names')
    ->get();
2 likes
Cronix's avatar

Wait...is your list of names stored as a single column with comma separated names? I sure hope not...

jlrdw's avatar

Formulate your data correctly and use the greater than and less than symbols. Really there is nothing to this if you do it correctly.

murilo's avatar
Level 10

could explain better @jlrdw ? do you think that have an easiest way than this ?

User::select(['id', 'names'])
    ->where('names', 'like', "a%")
    ->orWhere('names', 'like', "b%")
    ->orWhere('names', 'like', "c%")
    ->orWhere('names', 'like', "d%")
    ->orderBy('names')
    ->get();

becose imagine if I have to search from A to Z ...

Cronix's avatar

If you have to search a-z, then really you're just getting all, it would just be User::orderBy('names')->get().

Maybe if you say what you're actually trying to do it would help. My answer was based on your question "and I want to GET all names between Letters -> A to D " lol.

jlrdw's avatar

All I meant is greater than A and less than D. It was just kind of a tricky question is all.

I would not hard code the letters, I would use variables. What if you needed greater than AP, just a thought.

Tray2's avatar

You can also use regexp.

Db::select(SELECT id, names FROM users WHERE names REGEXP "^[A-D][a-z]+");
1 like

Please or to participate in this conversation.