thestepafter
thestepafter

Reputation: 618

Saving Polymorphic Relations in Laravel

I currently have a polymorphic relationship between phone numbers and contacts or organizations. I am using a morphMap to change the name of the parent relationship namespaced model to either contact or organization respectively.

Currently when I want to create a new phone number for an organization or contact I pass two URL parameters, parent_id=$record_id and parent_type=contact or organization. Then in my phone number controller I have the following which is super ugly:

    if ($request->parent_type == 'organization')
    {
        $parent_record = Organization::find($request->parent_id);
    }
    elseif ($request->parent_type == 'contact')
    {
        $parent_record = Contact::find($request->parent_id);
    }

    if ($parent_record)
    {
        $parent_record->phone_numbers()->save($phone_number);
        return redirect()->route($request->parent_type . '.show', ['id' => $request->parent_id])->with('notify', 'Phone number added!');
    }

I know that there has to be a better way for doing this since on every create or store method I duplicate this code. I just don't know how to make this better.

Upvotes: 0

Views: 383

Answers (1)

Ivan Yonkov
Ivan Yonkov

Reputation: 7034

$type = ucfirst($request->parent_type);
if (in_array($type, $allowedTypes) {
    $parent_record = $type::find($request->parent_id);
}

You can use the scope resolution operator to invoke static method from a class, when the last one is represented by string.

The catches here are two:

  1. The user can input a classname, you might not want to execute find(). Maybe a whitelist is needed
  2. The class is not part of this namespace - you need to use full qualified classname

Upvotes: 1

Related Questions