Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Updating Polymorphic Relations

Let's say I have 3 tables, Events, Matches and Training. Events is a polymorphic table, it can be either Match or Training.

------------------    -----------    --------------
|  Events        |    | Matches |    | Trainings  |
------------------     ----------    --------------
| id             |    | id      |    | id         |
| name           |    | home    |    | type       |
| eventable_id   |    | away    |    --------------    
| eventable_type |    -----------
------------------

Now, I create an event like this:

$match = Match::create(['home' => Team 1', 'away' => 'Team 2']);
$match->events()->create(['name' => 'Event name']);

Therefore I have this record in my Events table:

--------------------------------------
| 1 | 'Event name' | 1 | 'App\Match' |
--------------------------------------

And in Matches:

---------------------------
| 1 | 'Team 1' | 'Team 2' |
---------------------------

My Event Model:

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

My Match/Training Model:

public function events() {
    return $this->morphMany('App\Event', 'eventable');
}

However, what if I want to update that Event and I want to change it from Match To Training but keep the event.

Is there a more Eloquent way or do I have to do it like this ?

$event->eventable->delete();
$training = Training::create(['type' => 'Stamina Training']);
$event->update([
    'name' => $request->name,
    'eventable_id' => $training->id,
    'eventable_type' => 'App\Training'
]);
like image 356
Matis Avatar asked Apr 23 '26 17:04

Matis


1 Answers

Alright, I also faced the same issue and the solution is to use the associate function on the relation. Instead of deleting the "eventable" on the "event", you can simply associate another model instance to the morph relationship. like below.

$training = Training::create(['type' => 'Stamina Training']);
$event->eventable()->associate($training);
$event->update([
    'name' => $request->name
]);
like image 128
Sachin Kumar Avatar answered Apr 29 '26 10:04

Sachin Kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!