Laravel: Keep Displaying The View When Have Errors

newtocode :

I am new to Laravel. I have a problem, so I have a guestbook table that have 0 records

Table: guestbook +-------------------------------------------+ |id|name|email|phone|created_at|updated_at| +-------------------------------------------+

I want to get the first data using eloquent

$guestbook = Guestbook::first();
return view('guestbook.index', compact('guestbook'));

when I try to access it on browser, it shows error Trying to get property 'name' of non-object. I read some articles to set the APP_DEBUG to false, after that it shows error 500 server Error

The question is how can I see the view if there is no record on the guestbook table? Thank you in advance.

Dilip Hirapara :

APP_DEBUG false will hide your errors. but the error is still exists there.

As you said that in your guestbook table doesn't have any records.

While you fetching the first record by using first() method you're getting empty collection and it assign to $guestbook variable.

The best way to resolve is to use null coalescing operator.

In your blade file do it as below.

$guestbook->name ?? '';

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=12012&siteId=1