0

I'm working on an mlm site, And this is the code I have to get referrals of a referral down to the third generation. As for the requirements I must not use eloquent relationships. Here's my code;

public function matrix()
{      
    $referrals = DB::table('users')->where('referred_by', Auth::user()->referral_id)->get();


    if (!isset($referrals))
    {
        return view('matrix');
    }
    elseif(isset($referrals))
    {
        $referrals2gen = DB::table('users')->where('referred_by', $referrals[0]->referral_id)->get();
        if (!isset($referrals2gen)) 
        {
            return view('matrix2', ['referrals' => $referrals]);
        }
        elseif(isset($referrals2gen))
        {
            $referrals3gen = DB::table('users')->where('referred_by', $referrals2gen[0]->referral_id)->get();
            if (!isset($referrals3gen[0]))
            {
                return view('matrix3', ['referrals' => $referrals, 'referrals2gen' => $referrals2gen]);
            }
            elseif(isset($referrals3gen[0]))
            {
                return view('matrix4', ['referrals' => $referrals, 'referrals2gen' => $referrals2gen, 'referrals3gen' => $referrals3gen]);
            }

        }
    }
}  

Firstly, the code does not follow the Don't Repeat Yourself Principle. Secondly, it does not give all the referrals of my direct referrals. Any help I can get would be appreciated.

Sagar Gautam
  • 9,049
  • 6
  • 53
  • 84
Patrick Obafemi
  • 908
  • 2
  • 20
  • 42
  • You can use `first()` instead of `get() ` if you are only going to use the first element – gbalduzzi Sep 06 '17 at 08:40
  • 1
    You've not asked a question to help with. If it's just to help refactor your already working code, SO is probably not the place. – Jonnix Sep 06 '17 at 08:41
  • 1
    You've got a graph-like structure there. [this answer](https://stackoverflow.com/questions/192220/what-is-the-most-efficient-elegant-way-to-parse-a-flat-table-into-a-tree/192462#192462) might help on how to organise your query better. – apokryfos Sep 06 '17 at 08:43
  • i want to get all the records. – Patrick Obafemi Sep 06 '17 at 08:43
  • Jon Stirling the second question i asked was a problem. – Patrick Obafemi Sep 06 '17 at 08:45
  • You don't get all the records because you only do the query on the `$refellars[0]` id and not all the others. For the DRY, write a function to get all the referrers based on the specific id and use that with correct param instead of repeating the query over and over – gbalduzzi Sep 06 '17 at 08:46
  • okay. will do that. thanks – Patrick Obafemi Sep 06 '17 at 08:47

0 Answers0