Eloquent with Not Working

Hello I am having this problem with the laravel eloquent with. This code (in the docs) $debtHistory = DebtHistory::with('user.firstname')->get(); seems to not work, because it returns something lik Call to undefined relationship [firstname] on model [App\User]. what am I doing wrong here? Any idea? Thank you guys. :)

Note: If this helps.

I actually have an alternative method but I would like to do it in one query. This code my help you to know what I am trying to do.

$debtHistory = DebtHistory::whereBetween('created_at',[$filterData['from'], $filterData['to']])->where('amount', '>', '0')->get();
$excelData = [];
foreach($debtHistory as $history) {
     array_push($excelData, ['Name' => $history->user->firstname .' '. $history->user->lastname, 'Debt' => $history->amount, 'Date' => Carbon::parse($history->created_at)->format('Y-m-d')]);
}

I want to do that process in a eloquent model query is that possible?

1

1 Answer

This error says that User model doesn't have firstname relationship defined. You should load the data like this:

$debtHistory = DebtHistory::with('user')->get();

And display it with something like this:

@foreach ($debtHistory as $one)
    {{ $one->user->firstname }}
@endforeach

This will work if user() has belongsTo() relationship.

6

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.

Share this article
Twitter Facebook Pinterest