2

i follow some tutorial for tagging item on laravel so far i have schema table like this for tags table:

    public function up()
    {
    Schema::create('tags', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('tagname');
        $table->timestamps();
    });
    Schema::create('artikel_tag', function (Blueprint $table) {
        $table->bigInteger('tag_id')->unsigned()->index();
        $table->foreign('tag_id')->references('id')->on('tags')->onUpdate('cascade')->onDelete('cascade');
        $table->bigInteger('artikel_id')->unsigned()->index();
        $table->foreign('artikel_id')->references('id')->on('artikels')->onUpdate('cascade')->onDelete('cascade');
        $table->timestamps();
    });
}

artikels table:

       public function up()
        {
        Schema::create('artikels', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('judul');
            $table->timestamps();
        });
}

my artikel model:

class Artikel extends Model
public function tags()
{
    return $this->belongsToMany('App\Models\tag');
}   

tag model:

class tag extends Model
{
    protected $fillable = [

        'tagname',
];
    public function Artikel()
    {
        return $this->belongsToMany('App\Models\Artikel');
    }
}

my question how to get data like for example if i select artikel with tag horor so the other artikel with same tag will show up in same page. bacause right now it is broken if i select artikel with spesific tag on it the unrelated tag will show up too.

tyo
  • 83
  • 8

1 Answers1

0

In both model update relationship

class Artikel extends Model
public function tags()
{
    return $this->belongsToMany(tag::class,'artikel_tag','artikel_id','tag_id');
}  

and

class tag extends Model
{
    protected $fillable = [

        'tagname',
];
    public function Artikel()
    {
        return $this->belongsToMany(Artikel::class,'artikel_tag','tag_id','artikel_id');
    }
}

and in query

$tagName="horor ";

Artikel::with('tags')->whereHas('tags',function($query)use($tagName){
   $query->where('tagname',$tagName);
})->get();

Incase if you can refactor then follow naming convention Ref:Laravel 5 Naming Conventions

John Lobo
  • 14,355
  • 2
  • 10
  • 20