Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

kendrick's avatar

Undefined variable $doctor in create method

I am trying to create a simple reservation logic, where $user creates a formal $res at a $doctor, including a $ticket and an opportunity to select other usersthrough a select2 dropdown.

But somehow, when I try to make the select2 work, the variables $doctor and $res get lost (undefined) within the creation of $ticket for each users $user.

public function create(Request $request, Doctor $doctor){

      $user = Auth::user();
      $doctor = Doctor::where('id', $doctor->id)->first();


      $this->validate($request, [
          'date' => 'max:50', 
          'time' => 'date_format:H:i|max:140',  
      ]);

      if($res = $user->res()->create([ 
          'user_id' => auth()->user()->id,
          'doctor_id' => $doctor->id, 
          'date' => $request->input('date'), 
          'time' => $request->input('time'),   
      ])){
 
        $ticket = Auth::user()->ticket()->create([ 
            'user_id' => $user->id,
            'res_id' => $res->id,  
            'doctor_id' => $doctor->id,  
            'date' => $request->input('date'), 
            'time' => $request->input('time'),  
        ]);
 
        if ($users = $request->input('users'))
        {

          foreach($users as $user) // triggers a select2 dropdown (multiple)
          {
            User::whereIn('id', $request->input('users'))->get()->map(function($user) {       
               Ticket::create([ 
                    'user_id' => $user->id, // returns the correct id for chosen User
                    'doctor_id' => $doctor->id,  // undefined variable $doctor
                    'res_id' => $res->id,  // undefined variable $res
                    'date' => $request->input('date'), // undefined variable $request
                    'start' => $request->input('date'), // undefined variable $request 
                ]);
            }); 
          }
        }

      };

  }

How can I make them available within the foreach Loop?

0 likes
2 replies
tykus's avatar
tykus
Best Answer
Level 104

You need to pass the $doctor_id and $res_id variables into the Closure scope:

 User::whereIn('id', $request->input('users'))->get()->map(function($user) use ($doctor_id, $res_id) {

    // ...

Also, you are route-model binding the Doctor, so why perform another query here, it makes no sense:

$doctor = Doctor::where('id', $doctor->id)->first();
1 like
kendrick's avatar

As simple as that, wow. You are correct, $doctor_id was only for testing if I could reach it otherwise. Thank you.

Please or to participate in this conversation.