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)?
You may use inheritance or trait. Choose whatever you want.
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 { /* ... */ }
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.
The Best i can think of is to create a trait
and share among the classes.