I am trying to get data by using Laravel Eloquent HasMany (reverse) relationship but I am not getting access. Whenever I try, it shows Trying to get property 'name' of non-object
I have two models. Category and Article. Category hasMany Articles. Here are the models:
Category Model
protected $fillable = [
'user_id', 'name',
];
public function articles()
{
return $this->hasMany('App\Models\Article');
}
Article Model
protected $fillable = [
'user_id', 'headline', 'summary', 'body', 'status', 'cover_image', 'image_caption', 'image_credit', 'cover_video', 'video_caption', 'video_credit', 'category', 'meta', 'tags',
];
public function category()
{
return $this->belongsTo('App\Models\Category','category');
}
Article Controller
public function pendingposts()
{
$user = Auth::user();
$articles = Article::all();
return view('admin.article.pending-posts')->with(['user' => $user, 'articles' => $articles]);
}
View Blade (admin.article.pending-posts)
@foreach($articles->where('status', 'submitted')->sortByDesc('updated_at') as $article)
<tr>
<td >{{ $article->headline }}</td>
<td>{{ $article->category->name }} </td>
</tr>
@endforeach
here in blade, I can not access category through eloquent BelongsTo feature and I am not getting the reason behind getting the message:
ErrorException (E_ERROR) Trying to get property 'name' of non-object (View: C:\xampp\htdocs\joliadmin\resources\views\admin\article\pending-posts.blade.php)
with
e.g.Article::with('category')->get()
, and another reason may be you not have any data for category – Kushal Sutharreturn $this->hasMany('App\Article');
unless your models are in a model folder? Let me know if that's right and I can post as an answer for you :) – party-ring