Home > Blockchain >  How to loads relationships to a retrieved model using an existing scope methods
How to loads relationships to a retrieved model using an existing scope methods

Time:01-19

Suppose I have a $profile variable like so:

$profile = request()->user()->profile;

Later, I want to load some relationship that it has by utilizing the load() method, which can be executed using:

$profile->load('foo', 'bar', 'bar.logs');

I know the thing above. However, I happen to have a scope in the Profile model which has the same content as the code above, as follows:

class Profile extends Model
{
    // ....
    public function scopeWithFooBar($query)
    {
        return $query->with('foo', 'bar', 'bar.logs');
    }
}

Now, my question is, can I somehow use the withFooBar scope method to loads the relationships to $profile variable, simply so that I don't have to write the same content twice?

Please note that I'm aware as to how to use scope methods. But please share of what you have in mind. Thank you in advance!

CodePudding user response:

Yes, you can use the withFooBar scope method to load the relationships on the $profile variable, instead of using the load() method. Here's an example of how you can do this:

$profile = request()->user()->profile()->withFooBar()->first();

This will execute the withFooBar scope method on the Profile model and return the first result from the query. The result will have the relationships foo, bar, and bar.logs loaded, just like if you had used the load() method.

  • Related