3

I'm using Laravel 5.5.

I'm trying to get an object instance with the Query Builder of Laravel.

public function functionName(Request $request) {
    $seance = Seance::where('id_seance', '=', $request->idSeance)->get();

    return $seance->type_seance;
}

My model : Seance(id_seance, type_seance, capacite_seance, niveau_seance, avec_coach, date_seance, heure_seance).

However I get this error :

Exception: Property [type_seance] does not exist on this collection instance

Thank's for help!

Amit Gupta
  • 2,771
  • 2
  • 17
  • 31
Royce
  • 1,557
  • 5
  • 19
  • 44

3 Answers3

2

Use first() instead of get() to get an object instead of collection of objects:

$seance = Seance::where('id_seance', $request->idSeance)->first();

The difference between these methods is explained here.

Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
  • If he has set up the primary key correctly he could use `Seance::find($request->idSeance)` – Phiter Dec 26 '17 at 17:03
  • @Phiter with find, that's works! But with `where` it is the wrong way ? – Royce Dec 26 '17 at 17:07
  • `find()` is a shortcut for `where()->first()` and it searches by primary key only. Both ways are ok, but I'd use `find()` if you setup custom PK correctly. – Alexey Mezenin Dec 26 '17 at 17:13
  • Find tries to find a unique row from your table based on the table primary key (usually, we call it id). You can use where too, it's basically the same result, but find is more readable. – Phiter Dec 26 '17 at 17:13
2

Get() method return a collection object it's like an array, you need to use first method to get the first object:

public function functionName(Request $request) {
    $seance = Seance::where('id_seance', '=', $request->idSeance)->first();

    return $seance->type_seance;
}

You can use find() method too but id_seance should be the primary key of your table:

$seance = Seance::find($request->idSeance);
return $seance->type_seance;
YouneL
  • 8,152
  • 2
  • 28
  • 50
2

When using the get() method, it will return a collection rather than an instance of the model. I suggest using thefirst() method instead.

Better yet, useSeance::find($request->idSeance) or Seance::findOrFail($request->idSeance). This assumes that you've defined your primary key on your model correctly.

James Funk
  • 264
  • 4
  • 10