user151841
user151841

Reputation: 18046

Can't get id from simple model in Laravel 5.1

I have a model defined in Laravel 5.1. For some reason, I can't seem to get the id from it:

Psy Shell v0.5.2 (PHP 5.6.13-0+deb8u1 — cli) by Justin Hileman
>>> $survey = \App\Survey::where('id',54)->get();
=> Illuminate\Database\Eloquent\Collection {#682
     all: [
       App\Survey {#693
         id: 54,
         created_at: "2015-10-12 03:18:32",
         updated_at: "2015-10-12 03:18:32",
         location_id: 0,
       },
     ],
   }
>>> echo $survey->id;
PHP error:  Undefined property: Illuminate\Database\Eloquent\Collection::$id on line 1
>>>

What am I doing wrong?

Upvotes: 0

Views: 1395

Answers (2)

Basit
Basit

Reputation: 971

You are trying to access the id on collection and it will throw an error. Try modifying the query to

$survey = \App\Survey::where('id',54)->first();

by replacing get() by first() and it will work fine.

Or you can use find() to get the record by primary key $survey = \App\Survey::find(54);

Upvotes: 2

Jirennor
Jirennor

Reputation: 1289

You are using the 'get' method for retrieving your recrods. But in fact the 'get' method returns a collection of models.

So in order to get your id you need to use for example a foreach statement to loop over the collection.

But you could also use another option that will give you just a single model instance.

For example:

$survey = \App\Survey::where('id',54)->first();
$survey = \App\Survey::find(54);

Both will return a single model instance.

So after this you can just use:

echo $survey->id;

To access your id.

See this link for more information about this topic: Retrieving Single Models / Aggregates

Upvotes: 3

Related Questions