0

I want to return a array in my services relationship. In my output, I want something like:

services: {
 true: {...},
 false: {...},
}

The relationship it self is working. If I just

return $this->belongsToMany('App\Service', 'product_services', 'product_id', 'service_id')->wherePivot('includes_it', 1)

Then it works fine. But I want to go deeper. I want that the services method returns an array with a false, and a true key.

Like here:

public function services()
    {
        return [
            "true" => $this->belongsToMany('App\Service', 'product_services', 'product_id', 'service_id')->wherePivot('includes_it', 1),
            "false" => $this->belongsToMany('App\Service', 'product_services', 'product_id', 'service_id')->wherePivot('includes_it', 0)
        ];
    }

But what I get is:

Error: Call to a member function addEagerConstraints() on array

1 Answer 1

1

I think you are using the relationship feature of laravel in a wrong way in your second approach.

What you could do, for example, is to define two relationship functions on your model like this:

public function servicesIncluded()
{
    return $this->belongsToMany('App\Service', 'product_services', 'product_id', 'service_id')
        ->wherePivot('includes_it', 1);
}

public function services()
{
    return $this->belongsToMany('App\Service', 'product_services', 'product_id', 'service_id')
        ->wherePivot('includes_it', 0);
}

Then you could do something like this (assuming you model is called Product):

$products_included = Product::servicesIncluded()->get();
$prodcuts_excluded = Product::services()->get();
$result = [
    "true" => $products_included,
    "false" => $products_excluded
];

Or you could include the pivot column in your relationship like this:

public function services()
{
    return $this->belongsToMany('App\Service', 'product_services', 'product_id', 'service_id')
        ->withPivot('includes_it');
}
Sign up to request clarification or add additional context in comments.

2 Comments

My problem is, that I need it like: services : { true: ... false: ... }
see updated answer. If I understand you correctly that should give you your result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.