Vikram Anand Bhushan
Vikram Anand Bhushan

Reputation: 4896

one to many relationship in Laravel5 is not working properly

I have a collection controller

looks like this

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Middleware\Role;
use Illuminate\Support\Facades\Input;
use App\User;
use App\Invoice;
use Session;
use Validator;


class CollectionController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */

  public function __construct(){

    $this->middleware('role:collector'); // replace 'collector' with whatever role you need.
}
   public function getPayment($invoiceid){


         $id =$invoiceid;
         $invoice=Invoice::where('Id', $id)->with(['payments'])->get();


         return View('collectionmodule/payment')->with(array('invoice'=>$invoice));

 }

}

Then I have following models Invoice

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Invoice extends Model
{
    //
     protected $table = 'event_invoice';

     public function payments(){
        return $this->hasMany('App\paymentrecieved','invoice_id');
    }

    public function comments(){
        return $this->hasMany('App\comments','invoice_id');
    }
}

Paymentrecieved

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class paymentrecieved extends Model
{
    //
    protected $table = 'paymentrecieved';

    public function invoice(){

            return $this->belongsTo('App\Invoice');

        }


}

So for every Invoice there could be multiple payments .

So in My getPayment method I am writing Query like this .

$invoice=Invoice::where('Id', $id)->with(['payments'])->get();

Its getting me the Details from Invoice table . But its not getting me any Payment Details

Any one know why is this happening , According to me I have done the relationship properly

Thanks

Upvotes: 3

Views: 117

Answers (1)

Peter Kota
Peter Kota

Reputation: 8350

You use Id (with uppercase) for the primary key, but the Invoice model is looking for the id (with lowercase).

You should define the primary key in the Invoice model like this:

protected $primaryKey = 'Id'; 

Upvotes: 1

Related Questions