1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of questocat/laravel-referral package. |
5
|
|
|
* |
6
|
|
|
* (c) emanci <[email protected]> |
7
|
|
|
* |
8
|
|
|
* This source file is subject to the MIT license that is bundled |
9
|
|
|
* with this source code in the file LICENSE. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace Questocat\Referral\Traits; |
13
|
|
|
use Illuminate\Support\Facades\DB; |
14
|
|
|
use Illuminate\Database\Eloquent\Builder; |
15
|
|
|
use Illuminate\Support\Facades\Cookie; |
16
|
|
|
|
17
|
|
|
trait UserReferral |
18
|
|
|
{ |
19
|
|
|
public function getReferralLink() |
20
|
|
|
{ |
21
|
|
|
return url(config('referral.referral_url','/register?referral=')).$this->affiliate_id; |
|
|
|
|
22
|
|
|
} |
23
|
|
|
public function getRefererName() |
24
|
|
|
{ |
25
|
|
|
$refer = DB::table('users')->where('affiliate_id',$this->referred_by)->first(); |
|
|
|
|
26
|
|
|
return $refer->name; |
27
|
|
|
} |
28
|
|
|
public function getReferredUsersCount() |
29
|
|
|
{ |
30
|
|
|
$referred_users = DB::table('users')->where('referred_by',$this->affiliate_id)->count(); |
31
|
|
|
return $referred_users; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
public static function scopeReferralExists(Builder $query, $referral) |
35
|
|
|
{ |
36
|
|
|
return $query->whereAffiliateId($referral)->exists(); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
protected static function boot() |
40
|
|
|
{ |
41
|
|
|
parent::boot(); |
42
|
|
|
|
43
|
|
|
static::creating(function ($model) { |
44
|
|
|
if ($referredBy = Cookie::get('referral')) { |
45
|
|
|
$model->referred_by = $referredBy; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
$model->affiliate_id = self::generateReferral(); |
49
|
|
|
}); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
protected static function generateReferral() |
53
|
|
|
{ |
54
|
|
|
$length = config('referral.referral_length', 8); |
55
|
|
|
|
56
|
|
|
do { |
57
|
|
|
$referral = str_random($length); |
|
|
|
|
58
|
|
|
} while (static::referralExists($referral)); |
|
|
|
|
59
|
|
|
|
60
|
|
|
return $referral; |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: