Search code examples
arrayslaravel-5.3eloquent

Trouble capturing all parameters


Ok, I am trying to make a record and send an email notification/acknowledgement that the record has been recorded. I have a many to many relationship between a Players model and a Lessonhours model. The User model has a one to many with the Players model. I have run my 'store' method with several different modifications and I finally get my email to send. The problem is that I can't get the array of players that exist and send each an email. The multiple selections from my form are being properly inserted in their respective tables. When it comes to collecting the email data, I have come closest with the following code. The problem with THIS is that I only get one player instead of two or more when they exist. I hope this makes sense. Screenshots below.

Code and screenshot of $request array: Code and dd() for $request object.

The dd($request->players)

After query, not capturing the array of players.

Not capturing array of players dd($players)

Code to add an index to the $request object

Error message after trying to add index.

Players Model: Players Model

I am not very experienced with this and I am finding it difficult to pinpoint which documentation example to use. How can I get all of the emails addresses for sending after the insertion of record? I appreciate all help offered.

Lessonhours Model: Lessonhours Model

Store Lessonhours form Lessonhours form

User Model enter image description here


Solution

  • I'm not sure why you're putting an array inside an array for whereIn clause but if request players is already coming through as an array then your should just be able to do:

    whereIn('id', $request->players)
    

    Next you're only ever going to be sending one email because you're returning from inside the loop so it's going to send the first player one email and then return a response. To save have a temporary variable that you're not using again you could do:

    Players::with('users')->whereIn('id', $request->players)->get()
        ->each(function ($player) use ($lesshours) {
            Mail::to($player->users)->send(new ThankYouForLessonPackagePurchase($lesshours));
        });
    
    return back()->with(['success' => 'Player is enrolled in new Lesson Package.']);
    

    You don't have to do the above it's just another way to write it.

    Lastly, if you're always going to require player ids to be sent then you might as well add it to the validation array:

    'players    => 'required',
    'players.*' => 'exists:players,id',
    

    Hope this helps!