How do I make a referral program in Laravel?

2019-09-15 10:09发布

问题:

I am trying to create a program where other users can sign up using links of other already registered users. So, when one is referred, this is how the url would look like

mywebsite.com/register?ref_id=555 // ref_id is existing user id

I am using the default Laravel auth. There is a hidden input value which would contain the value of ref_id if it exists. My database has a column called referred_by which is an INTand set to null by default. When someone registers using the link with ref_id, that id will get saved into that user row. But the problem is it's getting saved as null everytime.

This is how the validator looks like in Auth/RegisterController.php

protected function validator(array $data)
{
    return Validator::make($data, [
        'first_name' => 'required|max:40',
        'last_name' => 'required|max:40',
        'email' => 'required|email|max:255|unique:users',
        'account_name' => 'required|max:80',
        'account_number'=> 'required|max:15',
        'bank_name'=> 'required|max:30',
        'phone_number' => 'required|max:15',
        'ref_id' => 'nullable|numeric',
        'username' => 'required|max:15|unique:users',
        'password' => 'required|min:6|confirmed',
    ]);
}

and this is how the create method look like

protected function create(array $data)
{
    return User::create([
        'first_name' => $data['first_name'],
        'last_name' => $data['last_name'],
        'email' => $data['email'],
        'account_name'=> $data['account_name'],
        'account_number' => $data['account_number'],
        'bank_name'=> $data['bank_name'],
        'phone_number'=> $data['phone_number'],
        'username' => $data['username'],
        'referred_id' => (int)$data['ref_id'],
        'password' => bcrypt($data['password']),
    ]);
}

Since ref_id is saved in the hidden input field as a string, I tried converting it into an integer before putting into the database but I am not able to get it to work. I am really confused on how I can achieve this. Please help me. Thanks in advance.

回答1:

Your create function has 'referred_id' => (int)$data['ref_id'], but your column name is referred_by, so just change referred_id to referred_by