3

I have a branch, branch_products, and invoices, and invoice_products models.

branch has many branch_products, branch has many invoices,

invoices has many invoice_products branch_products has many invoice_products

Now going back to the question, When creating a new invoice product, I want the BelongsTo field to only show me branch products that is in the branch of the invoice.

// InvoiceProduct.php

public function invoice() {
    return $this->belongsTo('App\Models\Invoice');
}

public function branchProduct() {
    return $this->belongsTo('App\Models\BranchProduct');
}

// I need something like this
public function getAvailableBranchProducts() {

    // get the branch id of the invoice, doesn't work
    $branchId = $this->invoice->branch_id;

    // get branch products that has the given branch id, doesn't work
    return whereHas('branch_products', function ($query) use ($branchId) {
        $query->where('branch_id', $branchId);
    })->get();
}

I don't know how I would solve this. I've tried WhereHas, local scopes, but no luck.

I need it for Laravel Nova.

3
  • When you are Going To Create a Invoice Product there is no relationship for that, Because Invoice Product is not created yet. It's yet to be created. Do you understand. Commented Oct 15, 2018 at 2:39
  • So is there no way to filter the branch products to only show branch products of the branch of the invoice? Commented Oct 15, 2018 at 14:32
  • You have to reconsider about your project design, I guess you are trying to create a new invoice and assign products to the invoice. May be you are selecting the 'Branch' first. So my advice is to When user select the Branch get the 'Branch Products' using an AJAX call and fill into 'Products' select box. Commented Oct 15, 2018 at 14:40

2 Answers 2

0

You can add a method inside of the Nova resource:

For example, if you had a BelongsTo field of users and needed to filter them by their type, you could add this method:

    public static function relatableUsers(NovaRequest $request, $query){
        return $query->where('type', 'editor');
    }
Sign up to request clarification or add additional context in comments.

Comments

-1

You have probably solved this already, but there is a package that adds a Nova field that could help you (or others reaching this page).

https://packagist.org/packages/orlyapps/nova-belongsto-depend

Quite simple to install and use. You can use it or get some ideas from it.

Comments

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.