1

here i am trying to get all the project->id, which match with team->project_id and relation is working but my using variable $users showing undefined. What could be the problem??

here is the controller code

public function index()
{
    if (Auth::user()->role->id == 1) {
        $projects = Project::all();
        $teams = Team::all();
        foreach ($teams as $team) {
            $users = User::whereIn('id', $team->members)->get();
        }
        return view('project.index', compact('projects', 'users'));
    } 
}
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
  • Possible duplicate of ["Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP](https://stackoverflow.com/questions/4261133/notice-undefined-variable-notice-undefined-index-and-notice-undefined) – Qirel Nov 24 '19 at 17:07
  • You need to defined it first, before the loop do `$users = null;`. Also note that your loop will overwrite `$users` for each iteration – Qirel Nov 24 '19 at 17:07
  • You should also define a relation instead, so you can do `$users = $team->users;` – Qirel Nov 24 '19 at 17:08
  • 1
    check you users table , probably the id is in your $team->members , is not exist in users table – Tanvir Ahmed Nov 24 '19 at 17:11

2 Answers2

2

You are not initializing the users out of the condition, so if there are no teams, there will be no users:

Try this instead:

$users = collect();
foreach ($teams as $team) {
    $users = User::whereIn('id', $team->members)->get();
}
return view('project.index', compact('projects', 'users'));

But keep in mind that your loop will override the users each time, so you will just get the users from the last team only :D

nakov
  • 13,938
  • 12
  • 60
  • 110
0

Your problem is in your loop.

There are some blurry parts in your code.

1) In every loop you over-write your $users variable: I will assume that you need an array so try something like:

        $users[] = User::whereIn('id', $team->members)->get();

*small note make sure that the column members in the Team table actually holds the ids.

2) The usage of compact() is correct but in case that your $user is empty then you will be trying to get an undefined property from it. In addition with the fact that you over-write your variable if the last itteration is empty then your $user is empty so you just return an empty array in your FrontEnd.

3) Using whereIn means that your column has more than 1 Ids. That's generally a bad practise. You should use a pivot table or store each record in different rows.

4) Predefine your array. If there are no teams, the foreach loop will never be accessed leaving you with a php error of undefined $users.

pr1nc3
  • 8,108
  • 3
  • 23
  • 36