I have 5 tables named Users, Chats, Buletins, Hartas, and Owners. All of these tables has many-to-many relationship with another table named Medias, via a pivot table named Mediables.
I need to use the polymorphic relationships because all of these 5 tables will be using the same Mediables table to store their relations with the Medias table.
For this thread, let me share my Buletins, Medias, and Mediables polymorphic relationships defined on their respective model files. I'll also shared the migration file for Mediables tablemy controller
Buletin Model:
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');
}
}
Mediable Model:
class Medialink extends Model
{
// no relation defined
}
Mediable 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 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 these inside a foreach loop ($buletins as $buletin):
{{ $buletin->user->name }} // Buletin belongsTo User & User hasMany Buletin
{{ $buletin->messages }}
{{ $buletin->created_at }}
Problem is, I didn't manage to echo this:
{{ $buletin->medias }} // gives me "[]" on the display
Please help me.
Already got the answer for this question. Problems lies in how I save the mediable_type inside my mediables table. Below is how I save it to get it to works:
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 Buletin model to get it to works.