Search code examples
laravelemailmessagesend

laravel send mail to


Good evening everyone, I have some issues, with send mail to: I have a code in controller, and have data taken from database with joins, this $survey variable shows gives me emails of the survey which belongs to team. But I need some how to send an email for all emails which I gets from $survey variable. When I put $survey variable inside $message->to($survey); it shows me Undefined variable

my code below , how can I use it. When I put in ->to(); normal one email adress it works, but I need to send same email to all team members

public function startSurvey(Request $req) {

    $nameSurvey = $req->input('SurveySelectBox');
    $startDate = $req->input('surveyStartDate');
    $endDate = $req->input('surveyEndDate');

    $data = array(
        'updated_at' => Carbon::now(),
        'started_at' => $startDate,
        'ended_at' => $endDate
    );

    DB::table('survey')->where('surveyId','=',$nameSurvey)->update($data);

    $survey = Survey::where('surveyId' , '=', $nameSurvey)
        ->join('team','team.teamId', '=', 'survey.teamId')
        ->join('teammembersall','teammembersall.TeamId', '=', 'team.TeamId')
        ->join('users','users.id', '=', 'teammembersall.UserId')
        ->select('users.email')
        ->get();

    Mail::raw('You have new survey to answer: http://localhost:8000/profile', function ($message) {
        $message->from('[email protected]', 'New Survey released');
        $message->to($survey);
    });

    return redirect('surveyDrafts');
}

Solution

  • You need to use use ($survey) to use the variable within the Mail anonymous function:

    Mail::raw('...text', function ($message) use ($survey) {
        $message->from('[email protected]', 'New Survey released');
        $message->to($survey);
    });
    

    You might also need to use ->pluck() and toArray() on the query result, to make the result an array:

    $survey = Survey::where('surveyId' , '=', $nameSurvey)
        // long query
        ->get()
        ->pluck('email')
        ->toArray();