Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in pivot table i stored post_id and category_id how can i get my Post category name from pivot table?

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 ???

like image 529
Md Foysal Avatar asked Nov 30 '25 22:11

Md Foysal


1 Answers

Post and Category both have many to many relationships, so you need another foreach for categories;

@foreach($post->categories as $category)
    {{$category->name}}
@endforeach
like image 57
bryceandy Avatar answered Dec 02 '25 13:12

bryceandy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!