tinyoverflow
tinyoverflow

Reputation: 2031

Untypical trying to get property of non-object...?

I have a problem with Laravel 5. I get a

trying to get property of non-object

error when I try to access an eloquent property in blade.

But it's not normal because this works fine:

{{ dd($item->relation->property) }}

While this throws the error:

{{ $item->relation->property }}

What's going on there? I already tried to clear the cache, I also deleted the compiled views.

Update 19.01. 14:24 EST

Here's the content of my database (All items in my item-dump):

It stops counting at ID22:

[2016-01-19 13:17:34] local.INFO: 10  
[2016-01-19 13:17:34] local.INFO: 11  
[2016-01-19 13:17:34] local.INFO: 12  
[2016-01-19 13:17:34] local.INFO: 19  
[2016-01-19 13:17:34] local.INFO: 21  
[2016-01-19 13:17:34] local.INFO: 22  
[2016-01-19 13:17:34] local.ERROR: ErrorException: Trying to get property of non-object in /home/vagrant/Code/Emerald/storage/framework/views/e18baccf6428ca42183f454a47f2cc9156379826.php:22

I did Log::info($item->id) before I access any other property of this object.

Upvotes: 0

Views: 1076

Answers (3)

tinyoverflow
tinyoverflow

Reputation: 2031

I finally got it! The relation to my item #22 (where the error occoured) was soft-deleted but now I did this and everything works fine again :)

$item->relation()->withTrashed()->get()->first()->property

Upvotes: 1

jardis
jardis

Reputation: 687

What is likely happening is when you are using $item->relation is your relation is returning an empty value. When a query in Laravel gets nothing from the database, you get a null result, of which there is no ->property to grab.

You can verify this by doing logging your $item->relation value, either to some local log file you then tail -f on, or by printing it to the screen with (new \Illuminate\Support\Debug\Dumper)->dump($item->relation); within your loop.

Upvotes: 0

Poyan
Poyan

Reputation: 6663

Could you perhaps be doing this in a loop, and thus the dd() finishes the execution after the first iteration?

Upvotes: 0

Related Questions