2

I have 4 models held together by 4 pivot tables:

User, Company, Phone, Address

The User and Company are both tied together to Phone with the pivot tables user_phone and company_phone.

User has a method: addDefaultPhone( Request $request ). It grabs $request->input() and creates a phone number and attaches it to the User.

The same exact method can be used in the Company class. How can I include addDefaultAddress to both classes (without copying and pasting of course)?

2 Answers 2

2

You may use inheritance or trait. Choose whatever you want.

Inheritance

Create a base class:

namespace App;
use Illuminate\Database\Eloquent\Model;

class ThingWithAPhone extends Model {
    public function addDefaultPhone() {
        /* Whatever you want... */
    }
}

Then both User and Company could extend this class:

// In the user file
class User extends ThingWithAPhone { /* ... */ }

// In the company file
class Company extends ThingWithAPhone { /* ... */ }

Trait

Create a trait:

namespace App;

class Phonable {
    public function addDefaultPhone() {
        /* Whatever you want... */
    }
}

Use this trait:

// In the user file
class User extends Model { 
    use Phonable;
    /* ... */ 
}

// In the company file
class Company extends Model {         
    use Phonable;
    /* ... */ 
} }

With trait you can create class which have X traits, and one other class with Y traits and some of these traits may be common to both classes.

Sign up to request clarification or add additional context in comments.

2 Comments

Seems to work. What if I have two parent classes: ThingWithAPhone and ThingWithAnAddress? How could I get a child class to use both of the parent classes?
Then you could use traits. I edited my answer to propose both solutions.
1

The Best i can think of is to create a trait and share among the classes.

2 Comments

Thanks for the reply. The method uses $this->phone() which is either the relationship of User to Phone or Company to Phone, so I'm not sure if a Trait could work without passing both the User or Company object and the $request to it. What do you think?
It will work you don't need to pass the object just use it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.