简体   繁体   中英

Undefined variable in Lumen

I am going to send email using gmail smtp in lumen, Everything working fine but one variable is always undefined, Please let me know where i am wrong

Here is my code

<?php

namespace App\Services;
use Illuminate\Support\Facades\Mail;

class MailService
{

    public static function send($mail_to = '', $title = '', $content = '') {
        Mail::send('mail', ['title' => $title, 'content' => $content], function ($message) {
            $message->from('noreply@gmail.com', 'Test Mail');
            $message->to($mail_to);
        });
    }
}

Here is the Controller

public function register(Request $request)
{

    $rules = [
        'name'          => 'required',
        'email'         => 'required|email|unique:users',
        'password'      => 'required|min:5',
        'phone'         => 'required|numeric|min:10',
        'business_name' => 'required|unique:users',
        'business_type' => 'required'
    ];

    $this->validate($request, $rules);

    $data = $request->all();
    $hashPassword = Hash::make($data['password']);

    $data['password'] = $hashPassword;
    $data['is_activated'] = 'false';

    $pin    = mt_rand(1000, 9999); 
    $token  = hash("sha256", $pin);

    $data['token']  = $token;
    $data['otp']    = $pin;

    $user = User::create($data);

    if ($user) {
        MailService::send($request->input('email'), 'OTP', $pin);
        return response()->json(['response' => true, 'message' => 'User registered Successfully', 'token' => $token], 201);
    } else {
        return response()->json(['response' => false, 'message' => ' Please check your credentials, Try again'], 400);
    }
}

Here is the error

{message: "Undefined variable: mail_to", exception: "ErrorException", file: "D:\\xampp\\htdocs\\api\\app\\Services\\MailService.php", line: 12, trace: Array(28)}

exception: "ErrorException"

file: "D:\\xampp\\htdocs\\api\\app\\Services\\MailService.php" line: 12 message: "Undefined variable: mail_to"

You are missing $mail_to . you need to use it in function then you may use it otherwise you would get an undefined variable error as you're getting it now.

use($mail_to)

Here your code looks like below.

public static function send($mail_to = '', $title = '', $content = '') {
    Mail::send('mail', ['title' => $title, 'content' => $content], function ($message) use($mail_to) {
        $message->from('noreply@gmail.com', 'Test Mail');
        $message->to($mail_to);
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM