php - Null in relationship belongs to in laravel?

I have tableproducts
andjob_statuses
and there is a relation between them in migration products:
$table->unsignedBigInteger('job_status_id')->index()->nullable();
$table->foreign('job_status_id')->references('id')->on('job_statuses')->onDelete('set null');
In Product model:
public function job()
{
return $this->belongsTo(JobStatus::class);
}
in blade dd :
@foreach ($products as $product)
@dd($product->job)
@endforeach
I gotnull
The weird thing that when I do the same way but in tinker the relation is worked!
Answer
Solution:
you have to pass the foreign key in relationship. by default laravel assumes the foreign key as relationname_primarykey of related table. in your case the relationship name is job but the foreign key is job_status_id. so the relationship is not biulding. change like
public function job()
{
return $this->belongsTo(JobStatus::class, 'job_status_id');
}
and a note. as you are using nullable you should check for relationship existence first.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: property [id] does not exist on this collection instance.
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.