0

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]);
2
  • Could you be missing $ sign on the user variable in your foreach? Commented Sep 25, 2015 at 17:27
  • Sorry that was a typo for the question, updated it, I also double checked and I do get the error using $user->id. Commented Sep 25, 2015 at 17:41

2 Answers 2

1

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

$weeklyCallsArray[$user->id]
Sign up to request clarification or add additional context in comments.

1 Comment

I could of swore I tried that and it didn't work... but I tried it again and it works great. Thanks.
0

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

1 Comment

Thanks for the reply, I think it had some syntax errors but I almost have it working. This looks like the ideal way to get it done.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.