How to pass parameter in Laravel model relation

I made a category tree and I need to pass one parameter to relation, I can't pass them.

public function Child()
{
    return $this->hasMany(Category::class, 'parent_id', 'id');
}

but I want to use variable to pass in relation look like this.

public function Child()
{
    return $this->hasMany(Category::class, 'parent_id', 'id')->where(['owner_id' => $this->ownerId]);
}

then I try to use variable and receive nothing, but if I use hardcoded value then works well. Please help

Upvotes: 3

Views: 15348

Answers (2)

party-ring
party-ring

Reputation: 1871

You will need to add a constructor to your Child model (which extends the class Model).

private ownerId;

public function __construct(int ownerId)
{
    parent::__construct($attributes);

    $this->ownerId = $ownerId;
}

Then you can access this throughout your class.

public function child()
{
    return $this->hasMany(Category::class, 'parent_id', 'id')->where('owner_id', $this->ownerId);
}

You would do this if every time you wanted to instantiate your class Child, you would have to give it an owner:

$ownerId = 5;
$child = new Child($ownerId);

Alternatively, you could pass a parameter directly to that function from wherever you call it, like:

public function childWithOwner(int $ownerId)
{
    return $this->hasMany(Category::class, 'parent_id', 'id')->where('owner_id', $ownerId);
}

And you would call it: $this->childWithOwner(4);

As a tip I would encourage you to start your function names with a lowercase letter.

Upvotes: 3

Serhii Posternak
Serhii Posternak

Reputation: 504

$models = App\{YourMainModel}::with(['Child' => function ($query) use ($this) {
    $query->where(['owner_id' => $this->ownerId]);
}])->get();

Upvotes: 7

Related Questions