Your code is a mess. here is a cleaner version without using the models (since you did not say if they are in place)
Controller Code
public function show_friend_request()
{
$user_id = auth()->user()->id;
$senderIds = DB::table('friendships')->where('recipient_id', $user_id)->where('status', 'pending')->pluck('sender_id')->toArray();
$activeRequests = DB::table('users')
->whereIn('id', $senderIds)
->get(['first_name','last_name']);
return view('pages.friend_request')->with('activeRequest', $activeRequests);
}
Blade Code
@foreach($activeRequest as $key => $friend)
<li>
<div class="rounded badge-unread d-sm-flex border-0 mb-1 p-3 position-relative">
<!-- Avatar -->
<div class="avatar text-center">
<img class="avatar-img rounded-circle" src="assets/images/avatar/01.jpg" alt="">
</div>
<!-- Info -->
<div class="mx-sm-3 my-2 my-sm-0">
<p class="small mb-2"><b>{{$key}} : {{$friend->first_name.' '.$friend->last_name}}</b> sent you a friend request.</p>
<!-- Button -->
<div class="d-flex">
<button class="btn btn-sm py-1 btn-primary me-2">Accept </button>
<button class="btn btn-sm py-1 btn-danger-soft">Delete </button>
</div>
</div>
</div>
</li>
@endforeach
The requests in the controller can be fused into one
public function show_friend_request()
{
$user_id = auth()->user()->id;
$activeRequests = DB::table('users')
->leftJoin('friendships', 'friendships.sender_id', '=', 'users.id')
->where('friendships.recipient_id', $user_id)
->where('friendships.status', 'pending')
->get(['first_name','last_name']);
return view('pages.friend_request')->with('activeRequest', $activeRequests);
}
If you had the models and relations in place you can do
public function show_friend_request()
{
$activeRequests = User::whereHas('friendships', function ($friendship) {
$friendship->where('recipient_id', auth()->id())
->where('status', 'pending');
})->get(['first_name','last_name']);
return view('pages.friend_request')->with('activeRequest', $activeRequests);
}
solved How to print key value pair in Laravel using foreach loop [closed]