Home >Backend Development >PHP Tutorial >Why am I Getting 'Trying to get property of non-object' Error When Accessing User Name in Laravel 5 News Article?

Why am I Getting 'Trying to get property of non-object' Error When Accessing User Name in Laravel 5 News Article?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-15 12:29:02457browse

Why am I Getting

Unable to Access Object Property - Laravel 5

Issue Description

An attempt to echo out the name of a user from a News article is failing, resulting in the following error:

ErrorException: Trying to get property of non-object

Code Context

Models

class News extends Model
{
    public function postedBy()
    {
        return $this->belongsTo('App\User');
    }
}

class User extends Model
{
    protected $fillable = ['name', ...];
}

Schema

  • Table: users with a 'name' column
  • Table: news with a 'postedBy' column linking to users

Controller

public function showArticle($slug)
{
    $article = News::where('slug', $slug)->firstOrFail();
    return view('article', compact('article'));
}

Blade Template

{{ $article->postedBy->name }}

Explanation

The error occurs because the query in the controller (News::where('slug', $slug)->firstOrFail()) is returning an array, not an object. When trying to access ->postedBy on an array, the property is not recognized and the error is thrown.

To resolve the issue, you need to convert the array to an object before accessing the ->postedBy property. This can be done by using the findBySlug method on the News model instead of firstOrFail():

public function showArticle($slug)
{
    $article = News::findBySlug($slug); // Returns an object
    return view('article', compact('article'));
}

This will allow you to successfully access the ->postedBy property on the object and display the user's name in the Blade template.

The above is the detailed content of Why am I Getting 'Trying to get property of non-object' Error When Accessing User Name in Laravel 5 News Article?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn