When a model is linked to a variety of different models, but depending on the circumstance, we want to connect the most recent, the oldest, or a custom model.
Let’s use some code to test polymorphism one of many to check whether it works.
Consider a cat owner who keeps a large number of cats, all of which are confined to the neighborhood where the owner resides.
Now, if we want a cat owner or a location to be associated with one of the most ancient, cutting-edge, or conventional (depending on the circumstance), we might use the term Polymorphic One of Many Relationship in Laravel
Let’s create 3 models. One is for the area, one is for Cat and Another one is for Cat Owner . “-m” means we are creating migrations with the model.
Php artisan make:model Area -m Php artisan make:model Cat -m Php artisan make:model CatOwner -m
Then, in the migration table, include some columns.
class CreateCatOwnersTable extends Migration { public function up() { Schema::create('cat_owners', function (Blueprint $table) { $table->id(); $table->string('name'); $table->timestamps(); }); } public function down() { Schema::dropIfExists('cat_owners'); } } class CreateAreasTable extends Migration { public function up() { Schema::create('areas', function (Blueprint $table) { $table->id(); $table->string('name'); $table->timestamps(); }); } public function down() { Schema::dropIfExists('areas'); } } class CreateCatsTable extends Migration { public function up() { Schema::create('cats', function (Blueprint $table) { $table->id(); $table->string('name'); $table->unsignedBigInteger('catable_id'); $table->string('catable_type'); $table->timestamps(); }); } public function down() { Schema::dropIfExists('cats'); } }
Catable_id: It will be used to store the ID of the cat owner or the area.
Catable_type: It will be used to save the model name of the cat owner or the area.
Now we must use some method to connect the three models.
class CatOwner extends Model { use HasFactory; public function cat() { return $this->morphOne(Cat::class,'catable')->latestOfMany(); } } class Area extends Model { use HasFactory; public function cat() { return $this->morphOne(Cat::class,'catable')->oldestOfMany(); } } public function hasone() { $area = CatOwner::find(1); dd($area->cat); }