Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

COTIGA's avatar

Attempt to read property "slug" on null

Good morning, something really weird.

This code gives me the error Attempt to read property "slug" on null :

@php
// dd(url('cat/'.$mea->cat->slug.'/art/'.$mea->slug));
@endphp
<a href="{{ url('cat/'.$mea->cat->slug.'/art/'.$mea->slug) }}"> {{ $mea->titre }}</a>

If I uncomment "dd", it returns what I want:

"http://lfjp2.test/cat/etablissement-activites-periscolaires/art/les-activites-periscolaires-2023-2024" // resources/views/inc/alaune.blade.php

I'm on new Herd, Laravel 9 up to date, PHP8.2, all caches cleared. Relationships in models OK... I don't understand and can't find the solution :/

0 likes
9 replies
COTIGA's avatar

Simplified code

When I put {{ $mea->cat }} the view returns JSON and "slug" is present.

When I put {{ $mea->cat->slug }} I have the error: Attempt to read property "slug" on null

WTF 🤪

tykus's avatar
tykus
Best Answer
Level 104

Are you looping over a Collection of records; perhaps the first item in the Collection has a cat instance, but another/others do not? Check using @dump directive rather than dd:

@dump($mea->cat);
{{-- <a href="{{ url('cat/'.$mea->cat->slug.'/art/'.$mea->slug) }}"> {{ $mea->titre }}</a> --}}
2 likes
COTIGA's avatar

@tykus Yes, you were right.

A result was NULL, which should not happen. I must correct this.

I would consider using @dump from now on instead of DD.

Thanks for putting me on the right track

tykus's avatar

@COTIGA no worries, consider marking the thread solved if you are all set

nexxai's avatar

@COTIGA Just remember that @dd will exit after the first time it's seen, so if the problem is in the third instance of a model, you might never get there. Whereas @dump prints the same info, but does not end the process so that if the problem is in a future instance, you'll be able to see it.

Both tools have their uses.

Brainmaniac's avatar

Have you done:

php artisan config:clear
php artisan cache:clear
composer dump-autoload
php artisan view:clear
php artisan route:clear

I have that saved in my zshrc like so:

alias nukelaravel="php artisan config:clear
php artisan cache:clear
composer dump-autoload
php artisan view:clear
php artisan route:clear"

And I run it as a first step when it behaves really strange. 50% of the time it works

Snapey's avatar

@Brainmaniac strange. I code multiple projects every week and never use any of those commands.

(maybe composer dump if I have changed the name of a class, but I know thats part of the process)

If you NEVER cache routes and config in dev, you never need to clear it.

1 like
greywolves's avatar

Hello everyone, we need a developer teammate who can help us for a fee for our LMS project that we developed with PHP Laravel. If anyone is interested, we would like to meet. thanks

Please or to participate in this conversation.