DEV Community

Let's build a super simple referral system with Laravel

Simi Oluwatomi on August 06, 2019

Sometime ago, I was asked to build a referral system as part of the feature set of a Laravel web application. Referral systems were not new to me b...
Collapse
 
cyprian_dev profile image
Cyprian

So for those who would be using Laravel 8 with jetstream, this stack uses Fortify for authentication and i quote from laravel documentation 'Fortify does not provide its own user interface, it is meant to be paired with your own user interface which makes requests to the routes it registers'. if that is hard to understand then follow the laravel.com/docs/8.x/fortify#intro... for clarity or drop a comment below.

So let's get to the chase. The most important thing in this system is the session that Mr Simi set to cache a session variable named 'referrer' if the register route contains a ref query parameter. now go to App\Providers\FortiftyServiceProvider in the boot() method and paste the code below

Fortify::registerView(function(Request $request) {
if ($request->has('ref')) {
session(['referrer' => $request->query('ref')]);
}
return view('auth.register');
});
Now the code is doing the same as that in the registerController.

Secondly, after caching the ref=user and getting the user's id, you would need to pass in this data in the create() method. You will find this file in the App\Actions\Foritfy\CreateNewUser class. Like what i did, i replaced the codes in this file with that of the RegisterController and then pass in the

    $referrer = User::whereUsername(session()->pull('referrer'))->first();
Enter fullscreen mode Exit fullscreen mode

This is the code that pulls the referrer's credentials and parses it in to create a new user. Every other thing stays the same from the User class and from the migration class file too.

It worked for me because i was using laravel 8 for a referral system project. Like i said, drop a comment if you have any challanges below...Cheers

Collapse
 
reubendickson profile image
ReubenDickson

Thanks for this guys. I'm new to Laravel. The project I'm working on includes referrals system and I'm using Jetstream. Would you like to share what you've done please. Thanks

Collapse
 
simioluwatomi profile image
Simi Oluwatomi

Thanks! I should update this tutorial to reflect the changes in Laravel since it was written but I'm currently swamped with work.

Thanks once again

Collapse
 
cyprian_dev profile image
Cyprian

Okay boss.

Collapse
 
sarjid profile image
Sarjid Islam Habil • Edited

Thanks it's work fine in laravel 8..ihave make refferel system just 40 minutes.. Thanks for Your Help..

Collapse
 
dotcorps profile image
dotcorps

where to write Notification code

Collapse
 
simioluwatomi profile image
Simi Oluwatomi

You have to create a notification. Kindly refer to the notification section of the Laravel docs to get started with that

laravel.com/docs/8.x/notifications

Thread Thread
 
jhims profile image
Willy

How can I get in touch with you? a means of contact

Thread Thread
 
simioluwatomi profile image
Simi Oluwatomi

You can send me a tweet on X (formerly Twitter)

Thread Thread
 
jhims profile image
Willy

unable to send message by x

Thread Thread
 
simioluwatomi profile image
Simi Oluwatomi

Send me a mail at deifilius1@gmail.com

Collapse
 
clementn profile image
Clement

Very nice and very useful. Thank you.
I use it with a small change.

I moved the code to write the referrer into the session

    if ($request->has('ref')) {
        session(['referrer' => $request->query('ref')]);
    }
Enter fullscreen mode Exit fullscreen mode

from app/Http/Controllers/Auth/RegisterController.php to a custom made middleware app/Http/Middleware/CheckReferrer.php

That way, the ?ref=referrer can be used on any link on the website and not only on register?ref=referrer

P.S. The custom middleware can be created using the artisan command:
php artisan make:middleware CheckAge
then it has to be registered within app/Http/Kernel.php

    protected $middlewareGroups = [
        'web' => [
...........
            \App\Http\Middleware\CheckReferrer::class,
        ],
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jcarlosr profile image
Juan Ramos

Nice suggestion Clement. Although I think the session won't last much and it can be replaced if the user visits a page with a new ref parameter.
I need to keep the referrer value for at least 7 days and set the value only if it's not already there. For this particular case I think I will be using Cookies.

Collapse
 
simioluwatomi profile image
Simi Oluwatomi

This is great. I really didn't think about this use case as mine was only focused on registration

Collapse
 
legaciespanda profile image
Ernest Obot • Edited

Observation One

$referrer = User::whereUsername(session()->pull('referrer'))->first(); //Giving issues

should be
$session_data = session()->pull('referrer');
$referrer = User::whereUsername($session_data )->first();
//Fixed

I observed that laravel was having difficulty retrieving the referrerfrom the session and querying the database at the same time which was giving error when getting the id. The solution was to first get the referrer value from the session and pass it to the eloquent.

Observation 2
'referrer_id' => $referrer ? $referrer->id : null,

This is because $referrer does not return a boolean value instead a user object. So using it this way will return an error and of course logical error.

What I did in my case, was to check that referrer value from session was not null.

Should be
'referrer_id' => $session != null ? $referrer->id : null,

or
'referrer_id' => !is_null($session) ? $referrer->id : null,

Collapse
 
devsahm profile image
Fagbenro Damilare Samuel

You just saved me today. I almost wasted the whole day looking for solutions online. The logic is so simple and readable. It worked perfectly.

Collapse
 
simioluwatomi profile image
Simi Oluwatomi

I used to overthink things like this and think of very complex solutions that cover a lot of edge cases. But then I realized that if the solution to something is becoming too complex, maybe, just maybe I'm overthinking it. That has really helped me a lot

Collapse
 
christopherokonkwo profile image
Christopher C. Okonkwo

You really made it simple. Of all its clean without external packages. Kudos Bro

Collapse
 
simioluwatomi profile image
Simi Oluwatomi

thank you. that was the aim from the get go

Collapse
 
developia profile image
Opiaaustin

works fine for me just have an issue with, after using a referral link to register i get the error cant find call referralbonus, and i have imported the class, any ideas?

Collapse
 
sirg97 profile image
SirG

Thanks for this!

Collapse
 
hendisantika profile image
Hendi Santika

Very good article. Simple & good explanation. You just saved me today. The logic is so simple and readable. It worked perfectly.

Collapse
 
isaactobiloba profile image
Tobi

Everyone seems to understand the whereUsername() method on the User model. I can't find the explanation anywhere so I'm guessing it's a custom method?

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
cyprian_dev profile image
Cyprian

the session may not be set properly

Collapse
 
mahrmudasser profile image
Mahr Mudasser

Everything in this article is nicely and briefly described. I am bit confused about how to invite new user. I mean where and how to send invitation link to new user. ?

Collapse
 
kidnrks profile image
Tribe NG

you haven't updated this tutorial

Collapse
 
equimper profile image
Emanuel Quimper

Nice job. Really clean and well explain. Thank you :)

Collapse
 
simioluwatomi profile image
Simi Oluwatomi

Thank you! Glad that you found it super helpful

Collapse
 
smarthech profile image
ebuka john

This is really easy to comprehend. the best referral tutorial i have seen online. please i would appreciate if you can make a tutorial on multi-level referral system thank you

Collapse
 
simioluwatomi profile image
Simi Oluwatomi

At this point, I must ask what a multi-level referral system is. Maybe, just maybe I might be able to come up with something

Collapse
 
jhapali9 profile image
bhola9

I really appreciate your super simple referral system.... Now I can make my own referral system with your idea ... Thanks a lot !!!

Collapse
 
codingpowerx profile image
Coding PowerX

How to get referrals details like name , email , username from the referral instead of just the referral count ?

Collapse
 
azeezumor profile image
AzeezUmor

@foreach (Auth()->user()->referrals as $referral)
<ul>
<li>{{$referral->email}}</li>
</ul>
@endforeach

Collapse
 
azeezumor profile image
AzeezUmor

How to generate TOKEN for user registration URL instead of using USERNAME?

Collapse
 
mahrmudasser profile image
Mahr Mudasser

I want to use it to send invitation link on email . How can i use this .