artisticre's avatar

Why Isn't This Passing? I am Brain Dead Today

Controller

public function ourHistory()
    {
        $metaTitle = 'Title';
        $metaDescription = 'descriptio';
        $history = OurHistory::latest()->get();
        return view('pages.our-history',compact('history','metaTitle','metaDescription'));
    }

blade

{{$history}} shows all details in the database but if I change to {{$history->pagetitle}} (one of the columns in the database) says Property [pagetitle] does not exist on this collection instance.

0 likes
4 replies
jlrdw's avatar

if I change to {{$history->pagetitle}} (one of the columns in the database) says Property [pagetitle] does not exist on this collection instance.

Use a ternary to check for null, something like this:

{{ $history->pagetitle ?? 'None listed' }}

And is this correct?

$metaDescription = 'descriptio';

Should it be description?

JussiMannisto's avatar

$history is a collection of models, not a model. Use ->first() instead of ->get() to fetch a single model.

Snapey's avatar

The clue is in the error

Property [pagetitle] does not exist on this collection instance

you are asking for page title attribute on a collection not a single model.

Glukinho's avatar
Level 30

->latest() is not "give me the latest model". It applies order by created_at desc to a query.

So ->latest()->get() gives you a collection sorted by creation date, not a single model.

To retrieve a single latest model use ->latest()->first().

1 like

Please or to participate in this conversation.