To order the results by first name, you can use the SUBSTRING function in Postgres to extract the first name from the full name and then order by that. To order by the search term first, you can use a CASE statement to check if the first name starts with the search term and give it a higher priority.
Here's an example query:
$searchTerm = 'Mary';
$results = DB::table('names')
->orderByRaw("CASE WHEN SUBSTRING(name FROM '^[^ ]+') ILIKE '{$searchTerm}%' THEN 0 ELSE 1 END")
->orderByRaw("SUBSTRING(name FROM '^[^ ]+')")
->get();
This will order the results first by whether the first name starts with the search term (giving it a priority of 0), and then by the first name itself. The ILIKE operator is used for case-insensitive matching.
Note that this assumes that the full name is stored in a column called name. If your column has a different name, you'll need to adjust the query accordingly.