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

nrthbound's avatar

orderBy desc on relationship not working

I'm sure there is an easy solution to this, but for whatever reason, I just can't seem to crack it. I'm using Laravel 5.3 for reference.

I have a User model (using Laravels Auth scaffolding) with a relationship to Artwork

public function artworks()
    {
        return $this->hasMany('App\Artwork');
    }

My artwork model has a belongsTo relationship to the User

public function user()
    {
        return $this->belongsTo('App\User');
    }

I want to display all of the uploaded artwork in the Admin panel, but I want it to also include the owner of the artwork. So, this works fine:

$a = Artwork::orderBy('id', 'asc')->simplePaginate(1);

Then in my view, I do:

@foreach($a as $art)
    {{$art->user->name}}
@endforeach

Now, this works fine as well. However, if I try to change the order to DESC, I get Trying to get property of non-object. What am I missing? I've only been using Laravel for about a week, so please excuse my ignorance in advance, and thanks for your help!

0 likes
4 replies
Snapey's avatar

You probably have an artwork with no user ID (it only needs to be one to crash the foreach loop)

Also, make sure you eager load users otherwise you will have a sql query for every pass of your foreach loop.

$a = Artwork::with('user')->orderBy('id', 'asc')->simplePaginate(1);
2 likes
willvincent's avatar
Level 54

If you're using PHP 7 you might be able to get by with something like this:

{{ $art->user->name ?? 'n/a' }}

In case an artwork item doesn't have a user.

If that still doesn't work you'll probably have to check if the user is set/an object:

{{ is_object($art->user) ? $art->user->name : 'n/a' }}

or better yet, you could omit artwork without users from the query results:

// Select artwork that has a user, include the user, order descending, and paginate:
$a = Artwork::has('user')->with('user')->orderBy('id', 'desc')->simplePaginate(1);
1 like
nrthbound's avatar

Hmm, I'm at work now. I'll have to check the database to make sure I didn't accidentally delete a a user and forget to delete their associated artwork when I get home. That would explain it. Thanks guys. It's super appreciated it. I'll mark an answer once I get have time to test.

nrthbound's avatar

Yup, the User didn't exist. I really thought I was keeping track of that. I guess I need to pay more attention. Thanks guys so much for your help. Thanks to you Snapey for explaining why to use the eager load vs a regular query. I didn't quite understand the difference there.

Please or to participate in this conversation.