Mugluck
Mugluck

Reputation: 499

Laravel Using Collections to group duplicate table entries

Ok, so I'm trying to get the syntax for using collections. The laravel documentation and examples just make no sense to me right now. No-one's really talking about collections so:

I have two table entries, one for regions and one for countries. I'd like to be able to do something like group countries by region, so there's no printing of the duplicate regions. In php it makes sense. But in laravel, I don't get how their syntax works.

I'd like to get something like this:

Region A

Region A

etc etc

So how's it done?

This is my controller:

    <?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use App\Http\Requests;

class SortController extends Controller
{

    public function index(){
        $infos = DB::table('list_countries')
            ->select('Region', 'Country')
            ->groupBy('Region')
            ->get();

       // $sorts = DB::table('list_countries')->get();
        return view('Sort', compact('infos'));
    }
}

This is my threadbare blade file:

@extends('layout')


@section('content')
    <h1>Hello</h1>
                @extends('layout')


@section('content')
    <h1>Hello</h1>
                @foreach($infos as $sort)

                    <div class="checkbox">
                        <label>
                            {!! Form::checkbox('agree', 'yes') !!} {{ $sort }}
                        </label>
                    </div>
                @endforeach
@stop

Testing @Ray Cheng's advice works:

However it prints this:

[{"Region":"Africa - North Africa","Country":"Algeria"},{"Region":"Africa - North Africa","Country":"Egypt"},{"Region":"Africa - North Africa","Country":"Libya"},{"Region":"Africa - North Africa","Country":"Mali"},{"Region":"Africa - North Africa","Country":"Mauritania"},{"Region":"Africa - North Africa","Country":"Morocco"},{"Region":"Africa - North Africa","Country":"Niger"},{"Region":"Africa - North Africa","Country":"Tunisia"},{"Region":"Africa - North Africa","Country":"Western Sahara"}]

Note that this is one category, the groupby is working, but it's including the objects it's grouping by.

The database table looks like this:

Database tables

Upvotes: 0

Views: 117

Answers (1)

Raymond Cheng
Raymond Cheng

Reputation: 2505

what you need to do is use collection function groupBy:

$infos = DB::table('list_countries')
        ->select('Region', 'Country')
        ->get()
        ->groupBy('Region')
        ->toArray();

Upvotes: 1

Related Questions