This is my Ctegory model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
public function posts()
{
return $this->belongsToMany('App\Post')->withTimestamps();
}
}
here is my Post Model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function categories()
{
return $this->belongsToMany('App\Category')->withTimestamps();
}
public function tags()
{
return $this->belongsToMany('App\Tag')->withTimestamps();
}
public function user()
{
return $this->belongsTo('App\User');
}
}
this is my index function
public function index()
{
$posts=Post::latest()->get();
return view('admin.post.index',compact('posts'));
}
this is my view page
@foreach($posts as $post)
<tr>
<td>{{ $post->id }}</td>
<td>{{ str_limit($post->title,'10') }}</td>
<td>{{$post->categories->pivot->name}}</td>
</tr>
@endforeach
laravel gives me this error when i wants to echo my category name..
ErrorException (E_ERROR) Property [pivot] does not exist on this collection instance. (View: C:\xampp\htdocs\Advanced_Blog_System\resources\views\admin\post\index.blade.php)
i just need to view the category name how can i solve this problem ???
Post and Category both have many to many relationships, so you need another foreach for categories;
@foreach($post->categories as $category)
{{$category->name}}
@endforeach
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With