KWIZ
KWIZ

Reputation: 5

Get array values to display inside an object in a @foreach loop using Laravel Blade

In a blade template, I have:

@foreach($users as $user)
 {{ $user->id }}  // this displays just fine, the number 1
 {{ $weeklyCallsArray{$user->id} }} // get "Undefined offset:" error
 {{ $weeklyCallsArray{1} }} // this works fine
@endforeach

How can I get the array to display with the corresponding user? I want to use something like:

$weeklyCallsArray{user->id}

Here is my query and return in the controller:

$users = DB::table('users')->get();
foreach ($users as $user) {
    $userId = $user->id;
    $countThisWeek = DB::table('calls')
        ->where('called_by', '=', $userId)
        ->where('calledd_on', '>=', Carbon::now()->startOfWeek())
        ->count();
    $weeklyCallArray[$userId] = $countThisWeek;
}

return view('users')
    ->with(['users' => $users])
    ->with(['weeklyCallsArray' => $weeklyCallsArray]);

Upvotes: 0

Views: 1192

Answers (2)

Ali Nazari
Ali Nazari

Reputation: 1438

You should use eloquent and you can load calls of the user with the user.

$users = User::with(['calls' => function($q){
     $q->calledd_on >= Carbon::now()->startOfWeek());
}]->whereUserId($id)->get();

Then in your view you can count the calls like this:

@foreach($users as $user)
   {{ $user->id }}
   {{ count($user->calls) }}
@endforeach

Upvotes: 0

user1669496
user1669496

Reputation: 33078

I think you are using arrays wrong in the view? I've never seen that syntax before.

$weeklyCallsArray[$user->id]

Upvotes: 1

Related Questions