Search code examples
phpmysqldatabaseeloquentlaravel-6.2

Laravel 6.2 : I get the same Id from different data in index() method


I work with Laravel and I need to get some reservations from my database.

I use the query builder :

 public function getReservation($date)
    {
        $reservations = DB::table('reservations')
                        ->select('*')
                        ->join('agendas', 'reservations.agenda_id', '=', 'agendas.id')
                        ->whereDate('arrivee', $date)
                        ->get();

        return response($reservations);
    }

Everything is fine except that I have the same ID for different resource and I don't know why ?

the response :

[
    {
        "id": 1,
        "created_at": "2020-02-07 12:30:28",
        "updated_at": "2020-02-07 12:30:28",
        "arrivee": "2020-02-12 13:00:00",
        "nbre_client": 4,
        "num_table": null,
        "remarque": null,
        "venu": 0,
        "formule": 0,
        "agenda_id": 1,
        "user_id": 1,
        "nom_client": "Stark",
        "prenom_client": null,
        "num_phone_client": "0658180058",
        "email_client": null,
        "confirmResa": null,
        "nameAg": "London"
    },
    {
        "id": 1,
        "created_at": "2020-02-07 12:30:28",
        "updated_at": "2020-02-07 12:30:28",
        "arrivee": "2020-02-12 13:30:00",
        "nbre_client": 2,
        "num_table": null,
        "remarque": null,
        "venu": 0,
        "formule": 0,
        "agenda_id": 1,
        "user_id": 1,
        "nom_client": "Banner",
        "prenom_client": null,
        "num_phone_client": "0658180058",
        "email_client": null,
        "confirmResa": null,
        "nameAg": "London"
    }
]

The ID in my database are different (Respectively 2 and 3)

Any ideas someone ?


Solution

  • Solution

    The duplicated ids is most likely the id from your agendas since they belong to the same agenda.

    You could change your select to:

    ->select('reservations.*')
    

    The Eloquent Way

    You could also accomplish what you have with Eloquent.

    First, you need to make sure you Reservation model has a BelongsTo relation with your Agenda model.

    public function agenda()
    {
        return $this->belongsTo(Agenda::class);
    }
    

    Then you can query it like this:

    Reservation::whereHas('agenda', function ($query) use ($date) {
        $query->whereDate('arrivee', $date);
    })->get();