-2

I am new to Laravel. I want to fetch all the values in id column from table skills. It is auto incrementing and the primary key of the table.

The following shows my function to get skills:

public function getSkillList(){
    $skill = Skills::orderBy('id', 'ASC')->get();
    echo $skill->id;

Property [id] does not exist on this collection instance.

I get this error. Can anyone please help to fix this?

matiaslauriti
  • 7,065
  • 4
  • 31
  • 43
pghasandi
  • 19
  • 7
  • `->get()` returns a Collection of `Skills` instances, like `[{id: 1}, {id: 2}, ...]`, so you can't access `->id`, since it doesn't know which instance you're trying to access. You need to iterate, like `foreach($skill as $skill){ echo $skill->id; }`. Or, `echo Skills::orderBy('id', 'ASC')->first()->id;` – Tim Lewis Jun 11 '21 at 15:20
  • 2
    Sidenote, this question is asked _multiple times per week on Stackoverflow_. Did you search your error at all before posting this? I'm voting to close as duplicate: [Property \[title\] does not exist on this collection instance](https://stackoverflow.com/questions/41366092/property-title-does-not-exist-on-this-collection-instance) – Tim Lewis Jun 11 '21 at 15:21
  • If you try to dd($skill); the response will be a collection. If you try to get $skill->id that error will be thrown because you are trying to access the id but it's not accessible that way. If you try to foreach every object, then you can access each id you like. – Kevin Jun 11 '21 at 15:49

2 Answers2

2

This question is known before, you just have to search for your error and you will find a lot of answers.

however hier is your answer:

$skills = Skills::orderBy('id', 'ASC')->get();

foreach($skills as $skill) 
{
echo $skill->id;
}
Moubarak Hayal
  • 191
  • 1
  • 7
1

get(); function returns a collection of your Skills entity. You have to use loop to get the id and other values.

public function getSkillList() {
    $skill = Skills::orderBy('id', 'ASC')->get();
    if (!empty($skill)) {
     foreach ($skill as $value) {
       echo $value->id;
     }
    } else {
     return [];
    }
}

to get particular row data use ->first() instead of ->get().

$skills = Skills::orderBy('id', 'ASC')->first();
echo $skills->id;

Also, you can get more information from Laravel docs.

Jayant
  • 280
  • 2
  • 6