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

Sqrcz's avatar

First letter of each column value

Hello to everyone here ;)

I'm noob with Laravel (and forcing my self to OOP ;) )...

I have odd thing to do... i need to pull somehow from database first letters from string value in specific column...

for example... i have movies table... with column titles:

title / A Clockwork Orange / Alien / Back to the Future / Blade Runner / E.T. the Extra-Terrestrial / Star Wars / Terminator 2: Judgment Day

and the result i want to achieve is list of all first letters (without repeating)... like so:

A, B, E, S, T

What would be the best way of getting that? :)

Thank You!

0 likes
6 replies
JarekTkaczyk's avatar
Level 53

I suppose MySQL:

$letters = Movie::selectRaw('substr(title,1,1) as first')->lists('first');

// remove duplicates
array_unique($letters);

// you may want to sort the letters as well
array_unique($letters, SORT_LOCALE_STRING);

// and you may want to reset the keys
array_values(array_unique($letters, SORT_LOCALE_STRING));
1 like
Sqrcz's avatar

wow. Nice ;)

Looks so easy :P

Dziękuję ;)

djave_co's avatar

Thanks for this, I also used distinct and orderBy in the query to get everything ready to go immediately:

$dbLetters = Terms::selectRaw('substr(title,1,1) as letter')->distinct()->orderBy('letter')->get()->pluck('letter')->toArray();
Cronix's avatar

@djave_co You can remove get(). pluck() will execute the query so get() is extra there. You also probably don't really need toArray(). It still returns an eloquent collection, which is an array you can iterate over.

Please or to participate in this conversation.