Nikk96
Nikk96

Reputation: 83

is There A Laravel PHP Function To Show Database Records Without Duplicates?

I need to be able to bring back records from an SQL stored procedure and display them. but I do not want to show duplicates.

I have stored a procedure that brings back all records where ID = the selected ID. It then displays something like this

id value
12 34
12 34
12 33
12 33

I need to bring back only one occurence where ID = 12 and value = 33, and one occurence where ID = 12 and value = 34

I'm working in a PHP laravel framework, I know that

DB::selectOne will bring back a single column, and that DB::select will bring back all records. Is there a laravel/PHP function that will bring back records and will only show one of each value? like so:

id value
12 34
12 33

Upvotes: 1

Views: 7583

Answers (4)

bay_beast
bay_beast

Reputation: 11

You can use groupBy() which will remove your duplicate record and read it as a single record. You have to use Select() before groupBy(). I.e. select('require name') then groupBy('require name').

TABLENAME::Select('require name')->groupBy('require name')->get();

Upvotes: 0

Atika
Atika

Reputation: 1067

Yes. To display a single occurrence, you must use "distinct"

$result = DB::table('YourTableName')
->select('id', '//other columns')
->distinct()
->get();

Upvotes: 2

Gazmend Sahiti
Gazmend Sahiti

Reputation: 438

Use distinct as shown in documentation. Distinct will remove the duplicate records.

$data = DB::table('{{table_name}}')->select('id', 'desired_column')->distinct()->get();

Upvotes: 0

V-K
V-K

Reputation: 1347

You can do it through MYSQL:

SELECT id, col2, col3, col4
FROM yourtable
GROUP BY col2, col3;

or something like that though Eloquent:

$data = Model::select('id', 'value')->groupBy(['id', 'value'])->get;

Upvotes: 0

Related Questions