Maison >développement back-end >tutoriel php >Pourquoi est-ce que j'obtiens l'erreur « Essayer d'obtenir la propriété d'un non-objet » lors de l'accès au nom d'utilisateur dans l'article d'actualité de Laravel 5 ?
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
Models
class News extends Model { public function postedBy() { return $this->belongsTo('App\User'); } } class User extends Model { protected $fillable = ['name', ...]; }
Schema
Controller
public function showArticle($slug) { $article = News::where('slug', $slug)->firstOrFail(); return view('article', compact('article')); }
Blade Template
{{ $article->postedBy->name }}
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.
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!