Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mlazuardy's avatar

Fixing Edit Tag [Property [name] does not exist on this collection instance]

I need more help to making Edit Post with Working Edit tag too, Based on laravel 5.4 Pivot tags episode 30-31 i making the tag and showing the post, but i have a problem when editing the tags in Post@edit

here the full of my Method

3 Tables

  1. Posts (id,title,body,image etc)
  2. post_tag(post_id,tag_id) 3.tags(id,name)

Tag.php (model)

<?php

namespace App;
use Illuminate\Database\Eloquent\Model;
class Tag extends Model
{
  protected $table = 'tags';
    protected $fillable = [
        'name'
    ];
    public function posts()
    {
      return $this->belongsToMany('TCG\Voyager\Models\Post','post_tag','tag_id','post_id');

    }
    public function getRouteKeyName()
    {
      return str_slug('name');
    }
}

For Information, The Post Model is base on Laravel Voyager Admin where located in TCG\Voyager\Models\Post',

Post.php (model)

class Post extends Model
{
    use Translatable;

    protected $translatable = ['title', 'seo_title', 'excerpt', 'body', 'slug', 'meta_description', 'meta_keywords'];

    const PUBLISHED = 'PUBLISHED';
    protected $guarded = [];

    public function save(array $options = [])
    {
        // If no author has been assigned, assign the current user's id as the author of the post
        if (!$this->author_id && Auth::user()) {
            $this->author_id = Auth::user()->id;
        }

        parent::save();
    }

    public function authorId()
    {
      return $this->belongsTo('App\User', 'author_id');
    }

    /**
     * Scope a query to only published scopes.
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     *
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopePublished(Builder $query)
    {
        return $query->where('status', '=', static::PUBLISHED);
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function category()
    {
        return $this->hasOne(Voyager::modelClass('Category'), 'id', 'category_id');
    }

    /**
     *   Method for returning specific thumbnail for post.
     */
    public function thumbnail($type)
    {
        // We take image from posts field
        $image = $this->attributes['image'];
        // We need to get extension type ( .jpeg , .png ...)
        $ext = pathinfo($image, PATHINFO_EXTENSION);
        // We remove extension from file name so we can append thumbnail type
        $name = rtrim($image, '.'.$ext);
        // We merge original name + type + extension
        return $name.'-'.$type.'.'.$ext;
    }

    public function comments()
    {
      return $this->hasMany('App\Comment');
    }

    public function tags()
   {
     return $this->belongsToMany('App\Tag');
   }


}

PostController.php

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

use TCG\Voyager\Models\Post;
use TCG\Voyager\Models\Category;
use Carbon\Carbon;
use App\Tag;
use App\Profile;
use App\Comment;
use App\User;
use Alert;
use File;
use Auth;
use Input;
use Illuminate\Support\Facades\DB;
use Image;
class PostController extends Controller
{
    //
    public function index(Request $request)
    {

      $posts = Post::latest()->where('status','PUBLISHED')->paginate(9);
      if (!$posts){
        abort(404);
      }

      if ($request->ajax()) {
        return view ('post.load',['posts'=>$posts])->render();
      }
      $archives = Category::selectRaw('name, slug')
      ->groupBy('name','slug')
      ->get()
      ->toArray();
      return view('post.index',compact('posts','archives'));
    }

    public function show ($slug)
    {

      $post = Post::where('slug',$slug)->where('status','PUBLISHED')->firstOrFail();
      $commentPaginator = $post->comments()->paginate(10);
      if(!$post){
        abort(404);}
      return view('post.show')->with(['post'=>$post,'commentPaginator'=>$commentPaginator]);
    }

    public function search(Request $request)
    {
      $keyword = $request->input('search');
      $posts= Post::where('title','LIKE','%'.$keyword.'%')->paginate(12);
      return view('post.livesearch',['posts'=>$posts]);
    }


    public function create(Request $request)
    {
      $categories = Category::all();
      return view('post.create',compact('categories'));
    }

    public function store(Request $request, Tag $tag)
    {

      $this->validate(request(),[
        'title'    =>'required|max:50',
        'body'    =>'required',
        'excerpt' =>'required',
        'category_id'  =>'required',

      ]);

      $post = new Post;
      $post->title = $request->title;
      $post->body  = $request->body;
      $post->slug  = str_slug($request->title);
      $post->excerpt = $request->excerpt;
      $post->category_id = $request->category_id;
      $post->meta_description = $request->excerpt;
      $post->meta_keywords = $request->title;
      $post->seo_title    = $request->title;
      //save Image
      if ($request->hasFile('image')) {
        $request->file('image')->store('public/posts/');
        $post->image = $request->file('image')->hashName('posts/');
                                      }

          $tags_id = [];
               if ($request->tags) {
                   $tags = explode(',', $request->tags);
                   foreach ($tags as $tag) {
                       $tag_ref = Tag::firstOrCreate(['name' => str_slug($tag,'-')]);
                       $tags_id[] = $tag_ref->id;
                   }
               }
               $post->save();
                Alert::message('Selanjutnya akan di Review Oleh Admin', 'Artikel Sukses Dibuat')->persistent('close');
                 $post->tags()->sync($tags_id);
          return redirect('/profile/post')->with('success','Post Berhasil dibuat');
    }
    //edit post
    public function edit($id)
    {
      $post = Post::with('tags')->find($id);

      if(is_null($post)){
        abort(404);
      }
      if($post->author_id != Auth::user()->id){
        abort(404);
      }

      $categories = Category::all();
      $tags = Tag::all();

      $tags = [];
      foreach ($post->tags as $tag) {
        array_push($tags, $tag->name);
    }

      if ($post->status == 'PUBLISHED') {
        abort(404);
      }
      return view('post.edit',compact('post','categories','tags'));
    }
      //delete posts
    public function destroy($id)
    {
      $post = Post::find($id);
      $post->delete();
      return redirect('/profile/post')->with('success','Artikel telah dihapus');
    }


}

the problem is in the method@edit

  public function edit($id)
    {
      $post = Post::with('tags')->find($id);

      if(is_null($post)){
        abort(404);
      }
      if($post->author_id != Auth::user()->id){
        abort(404);
      }

      $categories = Category::all();
      $tags = Tag::all();

      $tags = [];
      foreach ($post->tags as $tag) {
        array_push($tags, $tag->name);
    }

      if ($post->status == 'PUBLISHED') {
        abort(404);
      }
      return view('post.edit',compact('post','categories','tags'));
    }

and the view input is

          <input type="text" name="tags" id="tags" value="{{$post->tags->name}}" class="form-control">

when i use value {{$post->tags->name}}, whoops say

Property [name] does not exist on this collection instance. (View: D:\XAMPP\htdocs\commit\resources\views\post\edit.blade.php)"

i really dont know whats wrong with this method, please help me

0 likes
3 replies
matt_panton's avatar

Because the $post->tags relation will return a collection. You'll need to loop over them and output the tags individually. E.g:

@foreach($post->tags as $tag)
    <label>
        {{ $tag->name }}
        <input type="checkbox" value="{{ $tag->id }}" name="tags[]">
    </label>
@endforeach
mlazuardy's avatar
mlazuardy
OP
Best Answer
Level 2

fixed with this

return view('post.edit',compact('post','categories','tag'));

not tags but tag. i dont know why but it works

Please or to participate in this conversation.