I made 2 simple mistakes:
1) I removed User
object from findOrFail()
when looking for the mistake I made
2) I had specified user id's (friends) that did not exist in the databse, causing an error
I also improved the code a bit, by adding an optional parameter to get only x amount of users:
// App/User.php
public function getFriends($friends_to_get = null) {
$friendids = explode(',', $this->friends);
$friends = [];
$i = 0;
foreach ($friendids as $id) {
if (is_numeric($id)) {
$friends[] = User::findOrFail($id);
}
if (isset($friends_to_get) && $i < $friends_to_get) {
++$i;
}
if (isset($friends_to_get) && $i == $friends_to_get) {
break;
}
}
return $friends;
}
Now you can do something like this in your view:
@foreach ($user->getFriends() as $friend)
<p>Friend ID: {{ $friend->id }}</p>
<p>Friend Username: {{ $friend->username }}
@endforeach
Or if you want to get, for example, 6 friends only, you can do: $user->getFriends(6)
In my case, $user is the user of who's profile I'm currently viewing. If you want, you could also get your friends only, by doing Auth::user()->getFriends()
/Edit: Added is_numeric check in the foreach loop. This way you don't have to worry about first and last element in the column having an extra comma. Since explode adds an extra value to the array, if there's a comma in the end of the friends column. Now you can just add or remove x,
from/to the column every time and not worry about fetching an object, that does not exist.