Home > front end >  Laravel Mailable sending mail multiples times when it should send once
Laravel Mailable sending mail multiples times when it should send once

Time:11-30

I'm using Laravel 9. I made a system where an admin evaluates a player, it sends him a mail saying that he is accepted at the website.

In the view, when admin clicks accept, it goes into the evaluations controller and sends the mail if the value is the value of accept.

Controller:

public function update(Request $request, $id) {
        $evaluation = Evaluation::findOrFail($id);

        $evaluation->approved = $request->approved;

        $evaluation->save();

        if($evaluation->approved == 3) {
            $user = User::findOrFail($evaluation->idUser);
            $user->evaluation = 1;
            $user->save();
            Mail::to($user->email)->send(new EvaluationMailable());
        }

        return view('admin.evaluaciones');
    }

View:

<form method="POST" action="{{route('evaluation.update',$evaluaciones->id)}}">
    @csrf
    <input type="text" name="approved" value="3" hidden>
    <button type="submit" >Aceptar</button>
    @method('PUT')
</form>

What some users received:

enter image description here

CodePudding user response:

Why don't you add verification upon the value of the evaluation to check if it has not already the value 3 which seems to meet the criteria you "need" to send an email.

public function update(Request $request, $id) {
        $sendMail = true;
        $evaluation = Evaluation::findOrFail($id);
        if ($evaluation->approved != 3) {
          $evaluation->approved = $request->approved;
          $sendMail = false;
        }
        $evaluation->save();

        if($sendMail && $evaluation->approved == 3) {
            $user = User::findOrFail($evaluation->idUser);
            $user->evaluation = 1;
            $user->save();
            Mail::to($user->email)->send(new EvaluationMailable());
        }

        return view('admin.evaluaciones');
    }

It may prevent sending multiples emails with the same form to the same evaluation / user.

CodePudding user response:

Can you please check and share (after removing any sensitive data) your Email providers setup and share your routes definition ?

Does you Evaluation model have any Observer attached ?

  • Related