The issue with the current query is that it uses the take(1) method, which limits the number of results to one. Instead, we can use a subquery to get the latest row for each user in the user_tests table, and then join it with the users table to get the user's name. Here's an example query:
SELECT u.id AS user_id, u.name, ut.completed
FROM users u
JOIN (
SELECT user_id, MAX(id) AS latest_test_id, completed
FROM user_tests
GROUP BY user_id
) ut ON u.id = ut.user_id
To convert this to a Laravel query, we can use the DB facade:
$results = DB::table('users as u')
->join(DB::raw('(SELECT user_id, MAX(id) AS latest_test_id, completed FROM user_tests GROUP BY user_id) ut'), function ($join) {
$join->on('u.id', '=', 'ut.user_id');
})
->select('u.id as user_id', 'u.name', 'ut.completed')
->get();
This will return a collection of objects with user_id, name, and completed properties.