Search code examples
laravellaravel-5eloquentjquery-select2entity-attribute-value

how to retrieve one data in EAV laravel if there is the same data


I have a database with the EAV Entity-attribute-value model, if there is the same data how do I only display the same data once? for example i have table user

id  user_id     name   user_value_name   user_value
1     2         vandy  useraddress       new york
3     2         vandy  userscore_tesA    90
4     2         vandy  userscore_tesB    30
5     3         ahmad  useraddress       japan
6     3         ahmad  userscore_tesA    80
7     3         ahmad  userscore_tesB    70

How do I get my name to be displayed only once? here I will use jquery select2 to display the data

$('#name').select2({
      placeholder: "Choose User...",
      ajax: {
        url: "{{ route('getUserFullname') }}",
        dataType: "json",
        delay: 250,
        processResults: function(data) {
          return {
            results: $.map(data, function(obj) {
                    return {
                    "id": obj.user_id,
                    "text": obj.name,
                    };
            })
          };
        },
      }
    });

in my controller, I only take data from the database and json's return response

$user = DB::table(users)->get();
return response()->json($user);

Solution

  • You can use distinct method in Laravel's QueryBuilder to solve this.

    $user = DB::table(users)->distinct('name')->get();
    return response()->json($user);
    

    In essence, it is a pretty way in Laravel that calls SELECT DISTINCT in SQL...