Search code examples
phplaravellaravel-4eloquentmutators

Laravel 4 - getting total from related table


I have two tables, one called invoice, the other called invoice_products. invoice contains the basic info for the invoice, but no total. however invoice_products holds the actual items attached to the order. this allows me to customize the order simply by adding a new invoice_product. the total is done by running a function that loops through the attached invoice_products and adds them up. what i want to know is:

can i use a mutator or some other trick to have invoice->total already have it populated without calling the function to do so directly

$invoice = Invoice::find(1);
echo $invoice->total;

I've looked at the documentation for accessors and mutators, and it seems to be what i'm doing but i can't find any examples online of actually manipulating the tables related to the current model.

thanks.


Solution

  • Just add a new function total() to your model:

    public function total()
    {
        // You can access the model using $this
        // example: $this->id
        // ...
        // Your logic to get the count
        // ...
    
        $this->total = $theGeneratedCount;
        return $this;
    }
    
    $invoice = find(1)->total(); // returns a Invoice model
    echo $invoice->total;
    

    This way you could continue chaining. Else, you could just return the count, but then you won't be able to chain.

    ...
    return $theGeneratedCount;
    ...
    
    $invoice = find(1);
    echo $invoice->total(); // returns the count
    

    To get $invoice->total to work you need to specify a __get() magic method:

    public function __get($name)
    {
        if(method_exists($this, $name) return $this->{$name}()
        return parent::__get($name);
    }