<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Ogbonna Henry</title>
    <description>The latest articles on Forem by Ogbonna Henry (@hen8y).</description>
    <link>https://forem.com/hen8y</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1184569%2F3df35c01-a9e8-431a-92d7-e327f5128c11.png</url>
      <title>Forem: Ogbonna Henry</title>
      <link>https://forem.com/hen8y</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/hen8y"/>
    <language>en</language>
    <item>
      <title>Laravel referral system using referral code</title>
      <dc:creator>Ogbonna Henry</dc:creator>
      <pubDate>Sat, 14 Oct 2023 02:03:23 +0000</pubDate>
      <link>https://forem.com/hen8y/laravel-referral-system-using-referral-code-ddg</link>
      <guid>https://forem.com/hen8y/laravel-referral-system-using-referral-code-ddg</guid>
      <description>&lt;p&gt;So i was working on a project and decided... "heyy, why not add a referral system and encourage users to share the application". Searched the web but all solutions weren't what i wanted, I mean referral systems aren't new to me but this is going to be my first time building one with laravel and this is also my going to be my first blog post 🎉. So lets get to it,&lt;/p&gt;

&lt;p&gt;The referral is going to work like this:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;A user signs up and a code gets auto generated as their referral code which they can give to others &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;When a user registers, they're prompted to add a referral code&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The user whose referral code was used would be notified that someone registered with their code&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;We are going to be creating 2 migration tables. The user table and the referral table.&lt;br&gt;
Our eloquent Model should be a case where a user can be refered by another user and a user can refer many users but it's going to be (One to One) while we have a column that adds each time a new user uses an existing user referral code. &lt;br&gt;
First of, we create our laravel application&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; laravel new referral-app
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After installing laravel, we make the referral model, migration and controller&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan make:model Referral -mc
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we edit our migration table, first the users table 👇&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; public function up(): void
    {
        Schema::create('users', function (Blueprint $table) {
            $table-&amp;gt;id();
            $table-&amp;gt;string('name');
            $table-&amp;gt;string('email')-&amp;gt;unique();
            $table-&amp;gt;string('referral_status')-&amp;gt;default('off');
            $table-&amp;gt;string('referral_by')-&amp;gt;nullable();
            $table-&amp;gt;timestamp('email_verified_at')-&amp;gt;nullable();
            $table-&amp;gt;string('password');
            $table-&amp;gt;rememberToken();
            $table-&amp;gt;timestamps();
        });
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we edit the referral table&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; public function up(): void
    {
        Schema::create('referrals', function (Blueprint $table) {
            $table-&amp;gt;id();
            $table-&amp;gt;foreignId('user_id')-&amp;gt;constrained()-&amp;gt;cascadeOnDelete();
            $table-&amp;gt;string('referral_code')-&amp;gt;unique()-&amp;gt;nullable();
            $table-&amp;gt;integer('total_referred_users')-&amp;gt;default(0);
            $table-&amp;gt;timestamps();
        });
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We are using foreignId cause of our Eloquent relationship with the users table &lt;code&gt;One-To-Many&lt;/code&gt;.&lt;br&gt;
Let's not forget our auth 😉&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;composer require laravel/ui
php artisan ui bootstrap
php artisan ui bootstrap --auth
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's edit our models, starting with the User Model&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;protected $fillable = [
        'name',
        'email',
        'password',
        'referral_status',
        'referral_by'
];

public function referral(){
    return $this-&amp;gt;hasOne(Referral::class);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We did we just do?&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;First we added &lt;code&gt;referral_status&lt;/code&gt; and &lt;code&gt;referral_by&lt;/code&gt; to the $fillable in the User model&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Then we specified the eloquent relationship &lt;code&gt;hasOne&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;On the other hand the Referral model eloquent relationship should &lt;code&gt;belongsTo&lt;/code&gt; the User model and we add &lt;code&gt;user_id&lt;/code&gt;, &lt;code&gt;referral_code&lt;/code&gt; and &lt;code&gt;total_referred_users&lt;/code&gt; to the Referral model $fillable&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; protected $fillable = [
        'user_id',
        "referral_code",
        "total_referred_users"
    ];


    public function user(){
        return $this-&amp;gt;belongsTo(User::class);
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Using MySql, we're going to create a database &lt;code&gt;referral_app&lt;/code&gt; and link it to through our .env file.&lt;/p&gt;

&lt;p&gt;Now we migrate and the add &lt;code&gt;Auth route&lt;/code&gt; to our &lt;code&gt;routes/web.php&lt;/code&gt; file&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan migrate
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the web.php file add this👇&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Auth::routes();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now let's add referral code to every user who signs up but first we need a page for users to enter their referral code after signing up. We would create a new file in our view/auth folder called &lt;code&gt;referral.blade.php&lt;/code&gt; and place this code below in it&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@extends('layouts.app')

@section('content')
&amp;lt;div class="container"&amp;gt;
    &amp;lt;div class="row justify-content-center"&amp;gt;
        &amp;lt;div class="col-md-8"&amp;gt;
            &amp;lt;div class="card"&amp;gt;
                &amp;lt;div class="card-header"&amp;gt;{{ __('Referral') }}&amp;lt;/div&amp;gt;

                &amp;lt;div class="card-body"&amp;gt;
                    &amp;lt;form method="POST" action="{{ route('referral.verify') }}"&amp;gt;
                        @csrf
                        @method('PATCH')

                        &amp;lt;div class="row mb-3"&amp;gt;
                            &amp;lt;label for="referral" class="col-md-4 col-form-label text-md-end"&amp;gt;{{ __('Referral Code') }}&amp;lt;/label&amp;gt;

                            &amp;lt;div class="col-md-6"&amp;gt;
                                &amp;lt;input id="referral" type="text" class="form-control @error('referral') is-invalid @enderror" name="referral" value="{{ old('referral') }}" required autocomplete="referral" autofocus&amp;gt;

                                @error('referral')
                                    &amp;lt;span class="invalid-feedback" role="alert"&amp;gt;
                                        &amp;lt;strong&amp;gt;{{ $message }}&amp;lt;/strong&amp;gt;
                                    &amp;lt;/span&amp;gt;
                                @enderror
                            &amp;lt;/div&amp;gt;
                        &amp;lt;/div&amp;gt;

                        &amp;lt;div class="row mb-0"&amp;gt;
                            &amp;lt;div class="col-md-8 offset-md-4"&amp;gt;
                                &amp;lt;button type="submit" class="btn btn-primary"&amp;gt;
                                    {{ __('Proceed') }}
                                &amp;lt;/button&amp;gt;
                            &amp;lt;/div&amp;gt;
                        &amp;lt;/div&amp;gt;
                    &amp;lt;/form&amp;gt;
                &amp;lt;/div&amp;gt;
            &amp;lt;/div&amp;gt;
        &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
&amp;lt;/div&amp;gt;
@endsection

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The form is being submitted to a patch route &lt;code&gt;referral.store&lt;/code&gt; which we are going to add the &lt;code&gt;web.php&lt;/code&gt; file later on, for now let's add this to the &lt;code&gt;web.php&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Route::get('/referral', function(){ return view('auth.referral');})-&amp;gt;name('referral');

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we let's get back to generating a referral code to every user who signs up&lt;/p&gt;

&lt;p&gt;Locate the  &lt;code&gt;RegisterController&lt;/code&gt; in &lt;code&gt;App\Http\Controllers\Auth&lt;/code&gt;. &lt;br&gt;
We're going to edit the &lt;code&gt;protected function create(array $data)&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Replace the function with this edited version&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;protected function create(array $data)
    {
        $user = User::create([
            'name' =&amp;gt; $data['name'],
            'email' =&amp;gt; $data['email'],
            'password' =&amp;gt; Hash::make($data['password']),
        ]);
        Referral::create([
            'user_id'=&amp;gt; $user-&amp;gt;id,
            'referral_code'=&amp;gt;Str::random(6),
        ]);

        return $user;

    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Also in your view/home.blade.php replace the existing code with this&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@extends('layouts.app')

@section('content')
&amp;lt;div class="container"&amp;gt;
    &amp;lt;div class="row justify-content-center"&amp;gt;
        &amp;lt;div class="col-md-8"&amp;gt;
            &amp;lt;div class="card"&amp;gt;
                &amp;lt;div class="card-header"&amp;gt;{{ __('Dashboard') }}&amp;lt;/div&amp;gt;

                &amp;lt;div class="card-body"&amp;gt;
                    @if (session('status'))
                        &amp;lt;div class="alert alert-success" role="alert"&amp;gt;
                            {{ session('status') }}
                        &amp;lt;/div&amp;gt;
                    @endif

                    &amp;lt;p&amp;gt;Your referral code is {{ auth()-&amp;gt;user()-&amp;gt;referral-&amp;gt;referral_code }}&amp;lt;/p&amp;gt;
                &amp;lt;/div&amp;gt;
            &amp;lt;/div&amp;gt;
        &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
&amp;lt;/div&amp;gt;
@endsection

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now let's add the referral part. First locate &lt;code&gt;App/Providers/RouteServiceProvider&lt;/code&gt; and edit &lt;/p&gt;

&lt;p&gt;Change from this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public const HOME = '/home';
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public const HOME = '/referral';
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now it's time to add our route &lt;code&gt;referral.store&lt;/code&gt; and verify referrals.&lt;br&gt;
In your &lt;code&gt;web.php&lt;/code&gt; file, add the patch route for storing the referrals&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Route::patch('/referral/store', [App\Http\Controllers\ReferralController::class, 'store'])-&amp;gt;name('referral.store');

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the ReferralController add the store function&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public function store(Request $request){
        $user = User::find(Referral::where("referral_code", $request-&amp;gt;referral)-&amp;gt;first()-&amp;gt;user_id);
        $total_referred_users = $user-&amp;gt;referral-&amp;gt;total_referred_users + 1;
        $user-&amp;gt;referral-&amp;gt;update(['total_referred_users'=&amp;gt; $total_referred_users]);
        DB::table('users')-&amp;gt;where('id', auth()-&amp;gt;user()-&amp;gt;id)-&amp;gt;update(['referral_by' =&amp;gt; $request-&amp;gt;referral]);
        Notification::route('mail', $user-&amp;gt;email)-&amp;gt;notify(new UserNotification());
        return redirect()-&amp;gt;action([HomeController::class,'index']);
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let me explain the code&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;First we got the user using the referral code that was submitted then we added to it counts of user&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;We then proceeded to update the new user's &lt;code&gt;referral_by&lt;/code&gt; column to add a referral code&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Finally, we send a notification to the user who referred that someone signed up with their referral code &lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Don't forget to make:notification to generate the email notification&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan make:notification UserNotification
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Edit the contents and replace with this code&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use App\Models\User;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class UserNotification extends Notification
{
    use Queueable;

    /**
     * Create a new notification instance.
     */
    public function __construct()
    {
        //
    }

    /**
     * Get the notification's delivery channels.
     *
     * @return array&amp;lt;int, string&amp;gt;
     */
    public function via(object $notifiable): array
    {
        return ['mail'];
    }

    /**
     * Get the mail representation of the notification.
     */
    public function toMail(object $notifiable): MailMessage
    {
        return (new MailMessage)
                    -&amp;gt;line("A user just joined ".getenv('APP_NAME')." using your referral code")
                    -&amp;gt;line('Thank you for using our application!');
    }

    /**
     * Get the array representation of the notification.
     *
     * @return array&amp;lt;string, mixed&amp;gt;
     */
    public function toArray(object $notifiable): array
    {
        return [
            //
        ];
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Our Laravel referral system using referral code is now done, don't forget&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan serve
npm install
npm run dev
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can check the code out on my github.&lt;br&gt;
&lt;a href="https://github.com/hen8y/laravel-referral-system"&gt;https://github.com/hen8y/laravel-referral-system&lt;/a&gt;&lt;br&gt;
In case you want to make the notifcation mail send faster, make sure to check laravel queue&lt;/p&gt;

&lt;p&gt;Follow me on X(Twitter) &lt;a href="https://x.com/hen8y"&gt;Twitter&lt;/a&gt;&lt;/p&gt;

</description>
      <category>laravel</category>
      <category>webdev</category>
      <category>tutorial</category>
      <category>beginners</category>
    </item>
  </channel>
</rss>
