php - Laravel 5.3 relationship returns wrong one
Get the solution ↓↓↓Solution:
Then to get the settings you can do:
$companies = Company::with('settings')->get();
Then access the first company's settings:
$companies ->first()->company_settings;
Since this returns a collection all of the collection methods are available to you:
https://laravel.com/docs/5.3/collections
To loop through them you could do:
$companies->each(function($company) {
$company->company_settings;
// Your logic here
});
Answer
Solution:
You can't build relation withsettings
in this query.whereHas()
works basically the same as has() but allows you to specify additional filters for the related model to check.
Try this:
Company::with('company_settings')
->whereHas('company_settings', function ($q) use ($company)
{
$q->where('company_id',$company->id);
})->get();
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: trying to access array offset on value of type null
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.