List The Duplicate Data Once

How to list all the data and only display once the duplicates?

If you just wanna show all the duplicates entry you can use the duplicates method. This will list duplicates. $collection->duplicates();

Show The Data Without Duplicates

List all and don’t repeat the duplicates

This post is about listing all data including the duplicate values. As laravel get method shows all the rows no matter how many times it is repeated.

Suppose, you have entries that have state names in the same table. And in some cases, you just want to call the data (column) without getting other columns.

The table structure:

public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('village')->nullable();
            $table->string('officename')->nullable();
            $table->string('subdistname')->nullable();
            $table->string('districtname')->nullable();
            $table->string('statename')->nullable();
            $table->timestamps();
        });
    }

In the above database table class, you can see the posts table has village details. In this record, a village will have the same state name and district name.

So the controller function will be like this:

public function states()
{
        $statename = Post::select('statename')
        ->selectRaw('count(statename) as qty')
        ->groupBy('statename')
        ->orderBy('qty', 'DESC')
        ->having('qty', '>', 1)
        ->get();
        return view('pages.state', compact('statename'));
}

A page with state names only. No village name or others detail.

You will get all the state names only once. No matter if it is repeated or not.

Related Posts