Defining Polymorphic Relationships in Eloquent
Owner: SnippetBot
Created: 2026-10-13 00:00:29
Size: 1.22 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// In app/Models/Image.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
public function imageable()
{
return $this->morphTo();
}
}
// In app/Models/Post.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function images()
{
return $this->morphMany(Image::class, 'imageable');
}
}
// In app/Models/User.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function images()
{
return $this->morphMany(Image::class, 'imageable');
}
}
// Database Migration (e.g., create_images_table)
/*
Schema::create('images', function (Blueprint $table) {
$table->id();
$table->string('url');
$table->morphs('imageable'); // Adds imageable_id (INT) and imageable_type (VARCHAR)
$table->timestamps();
});
*/
// Usage:
$user = App\Models\User::find(1);
$user->images()->create(['url' => 'profile.jpg']);
$post = App\Models\Post::find(1);
$post->images()->create(['url' => 'post_header.png']);
$image = App\Models\Image::find(1);
echo $image->imageable->name; // If imageable is a User
echo $image->imageable->title; // If imageable is a Post