I have a model like this
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Invoice extends Model
{
//
protected $table = 'event_invoice';
public function payments(){
return $this->hasMany('App\paymentrecieved','invoiceid');
}
public function comments(){
return $this->hasMany('App\comments','invoiceid');
}
}
Now if I want to get the invoice with all the payments and comments, How should I write the call
I did like this
$invoice = Invoice::where('Id','=',$id)->payments()->comments()->get();
Its throwing error
Call to undefined method Illuminate\Database\Query\Builder::payments()
Thanks & regards
Invoice::where(...)
returns you a builder (Illuminate\Database\Eloquent\Builder
). What you'd want is a model (Illuminate\Database\Eloquent\Model
), and you can get that by chaining a ->get()
(or first
, paginate
etc.) method at the end like Invoice::where(...)->get()
. Only with this model you can call for a relation.
Invoice::where('Id', $id)->first()->payments(); // <- This is a *query builder* for payments of that invoice
Invoice::where('Id', $id)->first()->payments; // <- This is the collection (array) of payments of that invoice
By the way, it's shorter and more readable to use find($id)
instead of where('Id', $id)->first()
.