Reputation: 1607
So I am trying to use BelongsTo to display customer details, here is my current code:
my controller:
$assignees = assignee::latest()
->whereNull('timeout')
->paginate(10);
return view('assignees.index',compact('assignees'))
->with('i', (request()->input('page', 1) - 1) * 5);
Assign table:
$table->string('original_filename')->nullable();
$table->string('custidno')->nullable();
$table->foreign('custidno')->references('custid')->on('customers');
$table->string('cardno')->nullable();
Customer table:
Schema::create('customers', function (Blueprint $table) {
$table->increments('id');
$table->string('custid')->index()->unique();
Assign Model:
public function cust()
{
return $this->belongsTo('App\Customer','custid');
}
in my view: I have got the following for loop which displays the "Assignee table" I want to replace the custidno field with the customer name, taken from Customer table.
index.blade.php:
<tr>
<td>{{ $assignee->id }}</td>
<td>{{ $assignee->datacenter }}</td>
<td>{{ $assignee->cust->name}}</td>
<td>{{ $assignee->refnumber }}</td>
I am getting the following error:
Trying to get property of non-object
Upvotes: 0
Views: 381
Reputation: 9055
In your Assign
Model :
public function cust()
{
return $this->belongsTo('App\Customer','custid');
}
You are using custid
which is inside customers
table. You need to specify custidno
which is the foreign key referencing custid
in customers
table.
Update it to :
public function cust()
{
return $this->belongsTo('App\Customer','custidno', 'custid');
}
That should give you correct records if exist. Then you can check further logic if data is not null then access its property.
Upvotes: 1
Reputation: 833
There is a fair chance that your query is returning null in it (No records). Now when you try to access its contents (which are nothing), you get error saying Trying to get property of non-object
Its better to print your output you are getting from your model query and then in your code, check if there are any record before processing them. like below:
if( count($assignee->cust) ){ // case there are some records against this assignee
{{ $assignee->cust->name}}
}
even better approach to debug this to do the following to see the output first in controller.
echo '<pre>'; // to proper display your output
print_r($assignee); // your object with everything in it
exit; // exit application to see your variable output
simply these line will help you debug your issue wherever possible.
Hope it helps :) Best of luck
Upvotes: 1