1

Code

$result = DB::table('disaster_rescue_data')
    ->join('users', 'disaster_rescue_data.username', '=', 'users.email')
    ->get();

Problem

I have this very simple join as mentioned in the above code. However when I render the data on a view or dd the $result, I get the same row duplicated and I can not figure out why. (The rows contain the same data.)

(I am using Laravel 5.4)

Can someone please help me figure out why? (I tried different techniques and none of them worked! Thanks.)

gfit21x
  • 141
  • 9

2 Answers2

0

to prevent duplication, you should use distinct() method, this method Returns only unique items from the result.

in order to do that, first you must stricly select what you want:

    $result = DB::table('disaster_rescue_data')
        ->select('disaster_rescue_data.*')
        ->join('users', 'disaster_rescue_data.username', '=', 'users.email')
        ->distinct()->get();
OMR
  • 11,736
  • 5
  • 20
  • 35
  • I tried this. But the result is the same. I only get the result. It gives me the result for the same row for all the records. – gfit21x Sep 14 '21 at 00:36
0

You could try using distinct in the query. Distinct removes duplicates in a result set.

For example

$result = DB::table('disaster_rescue_data')
->distinct()
->join('users', 'disaster_rescue_data.username', '=', 'users.email')
->get();

See https://laravel.com/docs/5.4/queries

EDIT: Ok, I am thinking you can now use groupBy to get the unique results. Although it's not clear what your data structure is so this is a guess to use "users.email". Maybe it could be "disaster_rescue_data.username" to group by. Experiment and see.

$result = DB::table('disaster_rescue_data')
->distinct()
->join('users', 'disaster_rescue_data.username', '=', 'users.email')
->groupBy('users.email')
->get();
  • I tried this. But the result is the same. I only get the result. It gives me the result for the same row for all the records. – gfit21x Sep 14 '21 at 00:35