One way to achieve this is by defining a one-to-one relationship between the two models and then using the magic __get() method to dynamically access the related model's attributes.
Here's an example:
// Model1.php
class Model1 extends Model
{
public function model2()
{
return $this->hasOne(Model2::class);
}
public function __get($key)
{
if ($this->model2 && $this->model2->getAttribute($key)) {
return $this->model2->getAttribute($key);
}
return parent::__get($key);
}
}
// Model2.php
class Model2 extends Model
{
// ...
}
With this setup, you can access the related model's attributes directly from Model1 like this:
$model1 = Model1::find(1);
$model1->model2; // returns the related Model2 instance
$model1->attr1; // returns the value of Model2's "attr1" attribute
$model1->attr2; // returns the value of Model2's "attr2" attribute
Note that this approach assumes that the related model's attributes have the same names as the accessors you want to define on Model1. If that's not the case, you'll need to modify the __get() method accordingly.