Eloquent Polymorphic Many-to-Many: Practical Example

Поделиться
HTML-код
  • Опубликовано: 2 авг 2024
  • If you have Tags that may belong to many Posts/Videos/Courses, how to search all records by a specific tag?
    Text article version of this video: laraveldaily.com/post/laravel...
    - - - - -
    Support the channel by checking out my products:
    - My Laravel courses: laraveldaily.com/courses
    - Laravel QuickAdminPanel: quickadminpanel.com
    - Livewire Kit Components: livewirekit.com
    - - - - -
    Other places to follow:
    - My weekly Laravel newsletter: us11.campaign-archive.com/hom...
    - My personal Twitter: / povilaskorop
  • ХоббиХобби

Комментарии • 7

  • @ronssijei
    @ronssijei Год назад +11

    Found a solution to this by creating a separate Taggable model.
    In your Taggable model you can add this.
    public function taggable(): MorphTo
    {
    return $this->morphTo();
    }
    and in your Tag model you can add this.
    public function related(): MorphOne
    {
    return $this->morphOne(Taggable::class, 'taggable');
    }
    and now your query would look like this.
    $tags = Taggable::with(['taggable'])->get();
    $tags->map(function ($tag) {
    return [
    'id' => $tag->taggable->id,
    'title' => $tag->taggable->title
    ];
    });

    • @LaravelDaily
      @LaravelDaily  Год назад

      Looks cool! Another possible solution, yes.

  • @UmbertoPanella
    @UmbertoPanella Год назад

    Hi. Instead of map to create same structure we can use appends on model (or with or other idea) also using eager loading method...(?) Will enjoy only on model specification.

  • @GergelyCsermely
    @GergelyCsermely Год назад

    Thanks

  • @florenciodev3867
    @florenciodev3867 Год назад

    I don't like to put logic on database.
    what about if I don't want to use laravel in future!
    I don't think that's professional.
    what's your opinion?

  • @user-hk3te3ql5p
    @user-hk3te3ql5p Год назад +1

    does quickadminpanel support this relationship?

    • @LaravelDaily
      @LaravelDaily  Год назад +2

      No we don't support polymorphic relations, it would be too complex to generate for all possible cases.