John Davidson

php - Setting op polymorphic relation - Laravel

0 comments
Message:


I'm trying to setup a polymorphic relation between Users & Organizations, to Repositories.


Repository.php


public function owner(): MorphTo
{
return $this->morphTo();
}

User.php


public function repositories(): MorphMany
{
return $this->morphMany(Repository::class, 'owner');
}

Organization.php


public function repositories(): MorphMany
{
return $this->morphMany(Repository::class, 'owner');
}

repository_has_owners table:
























id repository_id owner_id owner_type created_at updated_at
1 1 1 App\User


My Answer:
and different types of entities in Laravel. Here's how you can set it up:

1. Define the morphTo relationship in the User model:

php
public function entity()
{
return $this->morphTo();
}


2. Define the morphMany relationship in each of the entity models:

For example, if you have a Post model:

php
public function user()
{
return $this->morphMany(User::class, 'entity');
}


3. In your migration files, make sure to add the necessary columns for the polymorphic relationship. For example, in the users table, you can add the following columns:

php
$table->unsignedBigInteger('entity_id');
$table->string('entity_type');


4. When creating a new entity, you can assign it to a user like this:

php
$user = User::find(1);
$post = new Post();
$user->entity()->save($post);


5. You can retrieve the entity associated with a user like this:

php
$user = User::find(1);
$entity = $user->entity;


That's it! You should now have a polymorphic relationship set up between Users and different types of entities in Laravel.

Rate this post

3 of 5 based on 1301 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us