'Fetch names based on comma-separated ids using laravel relations

Using Laravel Model relation retrive names based on comma separated ids, can anyone help

for ex

$testing= Testpage::with('relationExample')->where('id',$id)->first();

{{testing->user_ids}} -> output is -> 5,9,15,17

instead of comma separated ids i want to display names with comma separated from users table using laravel relations



Solution 1:[1]

You need another query to explode by comma and make these ids as array and use whereIn('id',$ids)

$ids = explode(',',$testing->user_ids);
$users = Users::whereIn('id',$ids)->pluck('name');
$usersName = implode(',',$users);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Niklesh Raut