Mosharof Zitu
Mosharof Zitu

Reputation: 43

Laravel Eloquent BelongTo Model Access fails

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)

Upvotes: 0

Views: 352

Answers (2)

Mosharof Zitu
Mosharof Zitu

Reputation: 43

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

Upvotes: 0

user10186369
user10186369

Reputation:

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');
}

Upvotes: 0

Related Questions