Milkncookiez
Milkncookiez

Reputation: 7407

Access a protected field from queried Eloquent object

I query an entity:

$trip_redirect_id = Trip::whereUniqueToken($unique_token)->select('id')->get();

and try to get the id value with $trip_redirect_id->id or $trip_redirect_id['id'] but I get exception that the field is not present.

When I dump the $trip_redirect_id object, I can see the id and it's value and they are correct (I checked with the database). But how can I access the value inside php?

Upvotes: 1

Views: 891

Answers (2)

Milkncookiez
Milkncookiez

Reputation: 7407

Turns out, if I use auto-incrementing IDs, I can access the id attribute of the newly created model, right after it has been created in the DB.

So, this is the whole fix:

$trip->save();

$trip_redirect_id = $trip->id;

Upvotes: 0

user1669496
user1669496

Reputation: 33148

You are using get() which is going to be returning a Collection of objects so you won't be able to get the attributes of the models unless you iterate through the collection, even if it's just one item in the collection, or just grab the first record. Use this instead:

Trip::whereUniqueToken($unique_token)->select('id')->first();

Upvotes: 4

Related Questions