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

CedricBongaerts's avatar

Call to a member function orderBy() on a non-object

I'm trying to order my selected feedbacks by latest first and only showing 5 but when trying to achieve this, I get the error mentioned in the title.

It's prob simply something ridiculous or stupid that i'm missing but what am I doing wrong?

This is my code:

public function index(Tnb $tnb)
    {
        $user = Auth::user();
        $feedbacks = array();

        foreach($user->tnbs as $tnb)
        {
            foreach($tnb->feedbacks as $feedback)
            {
                $feedbacks[] = $feedback;
            }
        }

        dd($feedbacks->orderBy('created_at', 'DESC'));

        return view('profile.index', compact('user', 'tnb', 'feedbacks'));
    }
0 likes
6 replies
tangoG's avatar

$feedbacks is a array , you can't call orderBy() on a array .

CedricBongaerts's avatar

@tangoG Could you explain how I could fetch the latest 5 feedbacks out of the array, if possible? Thanks

bestmomo's avatar
Level 52

You can try with collection :

collect($feedbacks)->sortByDesc('created_at')->take(5)
3 likes
allanolivei's avatar

Convert array to collection:

$feedbacks = ['a', 'b', 'c', null];

$collection = collect($feedbacks)->map(function($name)
{
    return strtoupper($name);
})
->reject(function($name)
{
    return empty($name);
});

Please or to participate in this conversation.