Laravel: ErrorException 未定义的变量:ref

Laravel: ErrorException Undefined variable: ref

我运行进入错误:

ErrorException
Undefined variable: ref 

我已经解决了类似的问题,但 none 的解决方案对我有用。

我的 RegisterController 在第 52 行抛出错误

这是我的控制器代码:

class RegisterController extends Controller
{
/**
 * Display register page.
 * 
 * @return \Illuminate\Http\Response
 */
public function show()
{
    return view('auth.register');
}

/**
 * Handle account registration request
 * 
 * @param RegisterRequest $request
 * 
 * @return \Illuminate\Http\Response
 */
public function register(RegisterRequest $request){
    $user = User::create($request->validated());
    auth()->login($user);
    
    $email = $user['email'];
    $fullname = $user['fullname'];

    Mail::send('email.welcome',
        ['password' => $request->input('password')],
        function($message) use ($email) {
            $message->to($email)
            ->subject("Welcome to Primval");
        }
    );


    if(!($user->referrer===null)){
        $referrer = $user->referrer;
        $ref=DB::table('users')->where('username', $referrer)->get();

        Mail::send('email.referral-notification', ['referrer'=>$ref], 
                function($message) use($request){
                    $message->to($ref->email);
                    $message->subject('Direct referral');
            });
    }




    return redirect('/dashboard')->with('success', "Account successfully registered.");
    }
}

@tpojka所述:

Try with function($message) use ($request, $ref) {

此外,

$ref=DB::table('users')->where('username', $referrer)->get();

上面这行代码returns一个集合。

您可能需要单行。即:

$ref= \App\Models\User::firstWhere('username', $referrer);