Javacadabra
Javacadabra

Reputation: 5758

Retrieve unique entries from DB using Eloquent Laravel 4

I am using Laravel-4 to build an application. I am trying to make the best use of Eloquent ORM. Currently I am displaying a list of db entries which all have a number of tags associated with them To the right I display a grid of all the tags however it is showing duplicate tags. I would only like to show unique tags

This is my code:

<div class="tags-panel">
        <div class="tags-title"><h1>Tags</h1></div>
        <div class="tags-cloud">
            @foreach(Tag::distinct()->get() as $tag)
                <a href="#" class="tag"><span class="num"> {{ Tag::getAmount($tag->id) }} </span> {{$tag->name}} </a>
            @endforeach
        </div>
    </div>

Does Eloquent provide a way of only retrieving distinct entries from the db?

Upvotes: 1

Views: 310

Answers (2)

Marcus Olsson
Marcus Olsson

Reputation: 2527

To use the distinct()-function you have either have a select() in your chain, or use a field as an argument in your get()-function. For example:

$tags = Tag::distinct()->get(array('field'));

or

$tags = Tag::select('field')->distinct()->get();

You could also instead use groupBy('field') if you don't want to supply field names:

$tags = Tag::groupBy('field')->get();

Upvotes: 0

Ajay Kumar Ganesh
Ajay Kumar Ganesh

Reputation: 1852

Try using Tag::groupBy('field_name')->get()

<div class="tags-panel">
    <div class="tags-title"><h1>Tags</h1></div>
        <div class="tags-cloud">
            @foreach(Tag::groupBy('field_name')->get() as $tag)
                <a href="#" class="tag"><span class="num"> {{ Tag::getAmount($tag->id) }} </span> {{$tag->name}} </a>
            @endforeach
        </div>
    </div>

Upvotes: 2

Related Questions