0

When I run phpunit on my Laravel based project I get an error: ErrorException: Trying to get property of non-object

But only on phpunit, the page renders fine.

This is the line of code in my blade template that is de cause of the error:

{{ $user->roles->first()->display_name }}

When I replace this with the following (ugly) code the phpunit tests run ok:

@php ($role = preg_replace('/[^a-z\d ]/i', '', $user->roles->pluck('display_name')) ) 
{{ $role }}

The roles are eager loaded in the controller:

$users->load('roles');

Any idea why phpunit throws this error (and laravel not) and how to sove this in a better way?

Stacktrace from phpunit: https://paste.ee/p/dyMVs#

Laemol
  • 251
  • 2
  • 4
  • 1
    what are the output of {{ $user->roles }} and of {{ $user->roles->count() }} ? –  Nov 11 '16 at 13:11
  • Hi Yohanan, {{ $user ->roles }} outputs: [{"id":1,"name":"Admin","display_name":"Admin","description":"System administrator.","removable":false,"created_at":"2016-10-20 11:43:11","updated_at":"2016-10-20 11:43:11","pivot":{"user_id":3,"role_id":1}}] and ->count() all returns 1 – Laemol Nov 11 '16 at 13:19
  • Just {{ $user->roles->pluck('display_name') }} also works but outputs ["Admin"] – Laemol Nov 11 '16 at 13:22
  • I think the problem is that the role youre getting is an json object and not a collection.. try to see if it's converted to something else than a collection. –  Nov 11 '16 at 13:25
  • Thanks. I had the same idea but the strange thing is that collection methods seem to work. – Laemol Nov 11 '16 at 14:23

0 Answers0