Load Relationships Always, but Dynamically

You can not only specify what relationships to ALWAYS load with the model, but you can do it dynamically, in the constructor method:

1class ProductTag extends Model
2{
3 protected $with = ['product'];
4 
5 public function __construct() {
6 parent::__construct();
7 $this->with = ['product'];
8 
9 if (auth()->check()) {
10 $this->with[] = 'user';
11 }
12 }
13}

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 22 courses (477 lessons, total 38 h 20 min)
  • 2 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord