Search code examples
mysqllaravelmodeltagslaravel-7

Laravel Get Data From Relation Table


I'm building a project with Laravel 7.28. I have three tables named; projects, tags and project_tags. in project_tags table there is project_ids and tag_ids. It looks like this:

database_schema

I need to get all projects with their tag and secondly I need to get projects with certain tag. So What should I do in models? Which function and how should I use? And how can I get data?

I discovered rtconner/laravel-tagging package but is it the correct way to do it? Thanks for your help


Solution

  • You might want to create a many to many relationship between projects and tags.

    class Project extends Model
    {
        public function tags()
        {
            return $this->belongsToMany(Tag::class, 'project_tags')->withTimestamps();
        }
    }
    

    Then:

    // Get all projects with their tags.
    Project::with('tags')->get();
    
    // Get projects contain certain a certain tag.
    Project::whereHas('tags', function ($query) {
        return $query->where('tag', 'some value');
    })
    

    In addition, tags tend to be a polymorphic many to many relationships. So if you want to manually handle tagging in the long term, I suggest designing that way.

    Also, checkout spatie/laravel-tags package.