Home  >  Q&A  >  body text

I'm having trouble using polymorphic relationships in Laravel 9.x

I have 5 tables named "Users", "Chats", "Buletins", "Hartas" and "Owners". All of these tables have a many-to-many relationship with another table called Medias through a pivot table called Mediables.

I need to use a polymorphic relationship because all 5 tables will use the same Mediables table to store their relationships with the Medias table.

For this topic, let me share the Announcement, Media and Media polymorphic relationships defined in their respective model files. I will also share the migration files for the Mediables tablemy controller

Model Announcement:

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphToMany;

class Buletin extends Model
{
  public function user() 
  {
    return $this->belongsTo(User::class);
  }
  public function medias(): MorphToMany
  {
    return $this->morphToMany(Media::class, 'mediable');
  }
}

Media Model:

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphToMany;

class Media extends Model
{
  public function buletins(): MorphToMany
  {
    return $this->morphedByMany(Buletin::class, 'mediable');
  }
}

Medical model:

class Medialink extends Model
{
  // no relation defined
}

Treable Migration:

public function up()
{
  Schema::create('mediables', function (Blueprint $table) {
    $table->id();
    $table->unsignedBigInteger('media_id');
    $table->foreign('media_id')->references('id')->on('medias')->onDelete('cascade');
    $table->unsignedBigInteger('mediable_id');
    $table->string('mediable_type');
    $table->timestamps();
  });
}

In the controller file:

public function showbuletin ($id)
{
  $buletins = Buletin::where('id', $id)->orWhere('comment_id', $id)->paginate(5);
  return view('layouts.buletin.show-bbs')->with(compact('buletins'));
}

In show-bbs.blade.php I managed to echo all of this ($buletins for $buletin) in a foreach loop:

{{ $buletin->user->name }} // Buletin belongsTo User & User hasMany Buletin
{{ $buletin->messages }}
{{ $buletin->created_at }}

The problem is, I failed to respond to this:

{{ $buletin->medias }} // gives me "[]" on the display

please help me.

P粉366946380P粉366946380428 days ago479

reply all(1)I'll reply

  • P粉026665919

    P粉0266659192023-09-11 10:48:00

    This question already has an answer. The problem is how I save the mediaable_type in the mediables table. Here's how I saved it to work:

    Controller file:

    // store new buletin_media in mediables table
    if ($request->media_id) {
      foreach ($request->media_id as $key => $value) {
        Mediable::create([
          'media_id' => $value,
          'mediable_id' => $buletin->id,
          'mediable_type' => Buletin::class,
        ]);
      }
    }

    I have to save the exact announcement model for this to work properly.

    reply
    0
  • Cancelreply