最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - Attempt to read property "user" on null - Stack Overflow

programmeradmin2浏览0评论

Okay, I'm working on a social network with Laravel, and it turns out that from one moment to the next it sends me the error:

"Attempt to read property "user" on null"

Marking specifically the following line:

@if ($image->user->image)

This being in the following file:

`

@if ($image->user->image)
    <div class="container-avatar">
        <img src="{{ route('user.avatar', ['filename' => $image->user->image]) }}" class="avatar">
    </div>
@endif
<div class="data-user">
    <a href="">
        {{ $image->user->name . ' ' . $image->user->surname }}
        <span class="nickname">
            {{ ' | @' . $image->user->nick }}
        </span>
    </a>
</div>
<div class="image-container">
    <img src="{{ route('image.file', ['filename' => $image->image_path]) }}">
</div>

<div class="description">
    <span class="nickname">{{ '@' . $image->user->nick }}</span>
    <span class="nickname date">{{ ' | ' . FormatTime::LongTimeFilter($image->created_at) }}</span>
    <p>{{ $image->description }}</p>
</div>

<div class="likes">
    <?php
    $user_like = false; ?>
    @foreach ($image->likes as $like)
        @if ($like->user_id == Auth::user()->id)
            <?php $user_like = true; ?>
        @endif
    @endforeach
    @if ($user_like)
        <img src="{{ asset('img/heart-red.png') }}" data-id="{{ $image->id }}" class="btn-dislike">
    @else
        <img src="{{ asset('img/heart-black.png') }}" data-id="{{ $image->id }}" class="btn-like">
    @endif
    <span class="number_likes">{{ count($image->likes) }}</span>
</div>
`

And I don't understand why it happens, if a couple of minutes ago it was working correctly, in the database the user_id id can't be null, and the other data has an associated id

Fix the error so I can continue moving forward with my project

Okay, I'm working on a social network with Laravel, and it turns out that from one moment to the next it sends me the error:

"Attempt to read property "user" on null"

Marking specifically the following line:

@if ($image->user->image)

This being in the following file:

`

@if ($image->user->image)
    <div class="container-avatar">
        <img src="{{ route('user.avatar', ['filename' => $image->user->image]) }}" class="avatar">
    </div>
@endif
<div class="data-user">
    <a href="">
        {{ $image->user->name . ' ' . $image->user->surname }}
        <span class="nickname">
            {{ ' | @' . $image->user->nick }}
        </span>
    </a>
</div>
<div class="image-container">
    <img src="{{ route('image.file', ['filename' => $image->image_path]) }}">
</div>

<div class="description">
    <span class="nickname">{{ '@' . $image->user->nick }}</span>
    <span class="nickname date">{{ ' | ' . FormatTime::LongTimeFilter($image->created_at) }}</span>
    <p>{{ $image->description }}</p>
</div>

<div class="likes">
    <?php
    $user_like = false; ?>
    @foreach ($image->likes as $like)
        @if ($like->user_id == Auth::user()->id)
            <?php $user_like = true; ?>
        @endif
    @endforeach
    @if ($user_like)
        <img src="{{ asset('img/heart-red.png') }}" data-id="{{ $image->id }}" class="btn-dislike">
    @else
        <img src="{{ asset('img/heart-black.png') }}" data-id="{{ $image->id }}" class="btn-like">
    @endif
    <span class="number_likes">{{ count($image->likes) }}</span>
</div>
`

And I don't understand why it happens, if a couple of minutes ago it was working correctly, in the database the user_id id can't be null, and the other data has an associated id

Fix the error so I can continue moving forward with my project

Share Improve this question asked Mar 28 at 17:21 Vicente RodriguezVicente Rodriguez 7 1
  • 5 $image is null, so there's no object to get a relationship on – aynber Commented Mar 28 at 17:22
Add a comment  | 

3 Answers 3

Reset to default 1

If the user_id can't be null, it means that you don't load the association from the image, meaning $image doesn't embed its associated user.

Here is an example to retrieve an association

$image= Image::with('user')->get();

The string inside with correspond to the relationship method name in the Image model

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Image extends Model
{
    use HasFactory;

    protected $fillable = ['user_id', 'image_path', 'description'];

    /**
     * Define the relationship: An image belongs to a user.
     */
    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }
}

Possible Causes & Fixes

1. The Image Model is Null

If you're querying an image but it doesn't exist, $image will be null, causing the error when you try $image->user.

Check if $image exists before accessing user:

$image = Image::with('user')->find($imageId);  

if ($image) {
    $user = $image->user; 
}
else {
    return response()->json(['error' => 'Image not found'], 404); 
} 

2. The Relationship is Not Loaded

If user_id exists in the images table but you didn't load the user relationship, trying $image->user will result in null.

Use eager loading to load the user:

$images = Image::with('user')->get(); 

3. The Image Doesn't Have a User (Foreign Key Issue)

If the images table has a user_id column, but it's NULL, then $image->user will also be null.

Ensure that the user_id column is set properly:

  • If every image must have a user, define user_id as NOT NULL in the migration:
Schema::table('images', function (Blueprint $table) {
    $table->foreignId('user_id')->constrained()->onDelete('cascade'); 
}); 

4. The Relationship Method is Incorrect

Ensure your user relationship in the Image model is properly defined:

class Image extends Model {   
  
    public function user(){         
         return $this->belongsTo(User::class, 'user_id');    
    } 

}

Short answer: you have other points with $image->user->..., if $image->user is null there it will fail. It is expected behaviour.

Here’s a simplified version of the code you shared:

@if ($image->user->image)
    <div class="container-avatar">
        <img src="{{ route('user.avatar', ['filename' => $image->user->image]) }}" class="avatar"> <!-- Point A -->
    </div>
@endif
<div class="data-user">
    <a href="">
        {{ $image->user->name . ' ' . $image->user->surname }} <!-- Point B -->
        <span class="nickname">
            {{ ' | @' . $image->user->nick }}
        </span>
    </a>
</div>

I marked two important points:

  • Point A passes (inside the @if check).
  • Point B will throw the error if $image->user is null — and it isn’t inside any check.

There are several options how you can fix it, and the best one depends on your business logic:

Wrap the entire block

@if ($image->user)
    @if ($image->user->image)
        <div class="container-avatar">
            <img src="{{ route('user.avatar', ['filename' => $image->user->image]) }}" class="avatar">
        </div>
    @endif
    <div class="data-user">
        <a href="">
            {{ $image->user->name . ' ' . $image->user->surname }}
            <span class="nickname">
                {{ ' | @' . $image->user->nick }}
            </span>
        </a>
    </div>
... the rest of code
@endif

Use null-safe operator (Laravel 8+)

{{ $image->user?->name ?? 'Anonymous' }}

Provide default values

{{ $image->user->name ?? 'Anonymous' }}

My recommendation: Step back and handle it in the Controller with API Resources

It's best to prepare data in your controller using Resources. This way, you avoid mixing logic into your views.

Step 1: In your controller

public function show(Image $image)
{
    return new ImageResource($image);
}

Step 2: Create the resource

php artisan make:resource ImageResource

Step 3: Add default fallbacks

class ImageResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'avatar' => $this->user?->image ?? 'default-avatar.png',
            'nick' => $this->user?->nick ?? 'Anonymous',
            'full_name' => $this->user
                ? $this->user->name . ' ' . $this->user->surname
                : 'Anonymous',
            'image_url' => route('image.file', ['filename' => $this->image_path]),
            'description' => $this->description,
            'likes_count' => $this->likes->count(),
... add other fields
        ];
    }
}

You have more than one image?

No problem with this:

public function index(Request $request)
{
    $images = Image::all(); /** Or whatever your logic is 
Image::paginate()
*/
    
    return ImageResource::collection($images);
}

Passing it to blade template?

public function show(Image $image)
{
    return view('image', [$image => new ImageResource($image)]);
}

Final tip

If $image->user is unexpectedly null, double-check:

  • Whether the related user was soft deleted.
  • Whether the relationship is correctly defined in your Image model.
  • Whether eager loading was used (Image::with('user')->get()), to avoid lazy loading issues.
发布评论

评论列表(0)

  1. 暂无评论