Search code examples
phplaravelaffiliate

Laravel 6 - Affiliate Tracking User Registeration


enter image description here

As u guys can see in Image Above, i want to create referral_system that user can register and input referral_user from affiliate users.

And Referral_Code is unique for every user.

My Problem is I cant track Whom that code is.

My User Schema

       Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('referrer_id')->nullable();
            $table->foreign('referrer_id')->references('id')->on('users');
            $table->string('referral_code')->unique()->nullable();
            $table->string('referred_by')->nullable();
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });

My User Model

    public function referrer()
    {
        return $this->belongsTo(User::class);
    }


    public function referrals()
    {
        return $this->hasMany(User::class);
    }

In My UserController

       $referrer = User::where('name', auth()->user()->name)->first();

        $user = new User();
        $user->name = $request->name;
        $user->referral_code = substr(uniqid(), 0, 8); // for unique id
        $user->email = $request->email;
        $user->referrer_id = $referrer ? $referrer->id : null;
        $user->role = $request->role;
        $user->password = bcrypt($request->password);
        $user->save();

        return response()->json([
            'created' => true,
        ]);

Hope u guys will give me some idea and if u notice mistake in my code, pls correct me, I'll appreciate of all ur help.

Thanks...


Solution

  • I believe you're confusing Laravel relationships. hasOne, belongsTo, etc are not designed to be worked with in the same model. Basically what you're saying in Users model is that "User has a User where user_id = id" which makes no sense.

    I have no idea how you've designed your sql tables, I recommend you to split your entities in distinct parts and have pivot tables which binds them: users, affiliates, referrals

    - users table have     : "id"
    - affiliates table have: "id", "refferal_code"
    - refferals table have : "id", "affiliate_id", "user_id", "refferal_code"
    
    

    You tie a user with an affiliate through refferals table, through their IDs.

    Then create relationships between those. You may want to read more about Eloquent relationships as well. Hope this answer helps you.