Laravel query. Where unique

18,926

Solution 1

How about:

$jobs = DB::table('my_job_table')
    ->groupBy('job_id')
    ->get();

Eloquent:

  1. First, you need a model. You could generate this by using php artisan. php artisan make:model jobs (I assume you have done this already) This will create a model in /your_project/app/Job.php
  2. Now you can use Eloquent (here in a route, to see some output):

    Route::get('/jobs', function () { $jobs = \App\Job::groupBy('job_id')->get(); return $jobs->lists('job_id'); });

will return something like: [0,1,3,4] instead of [0, 1, 1, 1, 3, 4, 4, 4].

Solution 2

You could use DISTINCT.

DB::table('table')->select('job_id')->distinct()->get();
Share:
18,926
Evaldas Butkus
Author by

Evaldas Butkus

Updated on June 11, 2022

Comments

  • Evaldas Butkus
    Evaldas Butkus almost 2 years


    I got database table like this:

    **job_id**
        5
        5
        5
        6
        6
        7
        8
        8
    

    I want to write query, which could select only unique id's. By saying unique I mean select only these values once:
    5, 6, 7, 8

    Thanks in advance!

    • Damien
      Damien almost 9 years
      What code have you written to solve this problem? Please post your code and a (specific) problem.
    • Evaldas Butkus
      Evaldas Butkus almost 9 years
      At the moment my query picks all the job_id's. So when I do echo, my values doublicate. I want to echo these job_id's only once.
  • Evaldas Butkus
    Evaldas Butkus almost 9 years
    How do I do this with eloquent?
  • Evaldas Butkus
    Evaldas Butkus almost 9 years
    How do I do this with eloquent?
  • lukasgeiter
    lukasgeiter almost 9 years
    @EvaldasButkus exactly the same way
  • lukasgeiter
    lukasgeiter almost 9 years
    @EvaldasButkus exactly the same way