0
votes

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)

2
You should try with with e.g. Article::with('category')->get(), and another reason may be you not have any data for categoryKushal Suthar
Do all your posts have categorys?user5283119
@kushal Suthar, I tried by writing same code as you mentioned and still getting same error.Mosharof Zitu
Hi, I think your relationship may be wrong based on your file structure - try e.g. return $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
@swonder, yes, all articles/posts have a category.Mosharof Zitu

2 Answers

0
votes

You should try this:

    public function pendingposts()
{
    $user = Auth::user();
    $articles = Article::with('category')
        ->where('status', 'submitted')
        ->sortByDesc('updated_at')
        ->get(); 

    return view('admin.article.pending-posts')->with(compact('user', 'articles'));
}

@foreach($articles as $article)
    <tr>
    <td>{{ $article->headline }}</td>
    <td>{{ $article->category->name }} </td>
    </tr>
@endforeach

Updated Answer

Category Model

protected $fillable = [
    'user_id', 'name', 
]; 

public function article()
{
    return $this->hasMany('App\Models\Article');
}
0
votes

it worked after changing 'Article' tables 'category' column in 'category_id'. Thanks for helping.