1

I have a basic application which stores expenses in a table containing the following columns:

  • id
  • user_id
  • quote_id (nullable)
  • title
  • type
  • net

The quote_id column is linked to my quotes table; however, there can also be entries in the table without a quote_id.

I'm trying to output all expenses by using the relationship expenses() on my user model.

@foreach(Auth::user()->expenses as $e)
    {{ $e->id }}
    {{ $e->net }}
    {{ $e->quote->title }}
    {{ $e->quote_id }}
@endforeach

On my expenses model, I also have a relationship between the expense and the quote.

public function quote()
{
    return $this->hasMany('App\Quote', 'id','quote_id');
}

This is great for when there is always a quote_id in the table however some entries don't have a quote_id and I get the following error:

Undefined property: Illuminate\Database\Eloquent\Collection::$title

How can I resolve this?

3
  • Run a dd($e->quote) and see what it returns; betcha it isn't a single quote object. In fact I can say for sure that it is not, since the relationship is hasMany Commented Jul 18, 2016 at 21:56
  • @TimLewis I've updated to a belongs to but now I get can not find object which is expected.. How do I output even if no has one is found on quote_id? Commented Jul 18, 2016 at 21:59
  • 1
    {{ $e->quote ? $e->quote->title : "N/A" }} or something like that. Commented Jul 18, 2016 at 22:01

2 Answers 2

3

As far as I can tell (from your DB structure), each expense only has one quote not many. In other words, first order of business would be changing your $expense->quote() function to:

public function quote()
{
    return $this->hasOne('App\Quote', 'id', 'quote_id');

    // Since your column naming is standard, this should work too:
    // return $this->hasOne('App\Quote');
}

Then, since quote_id can be null, you still need to check that the expense's quote() is an object. Something like this can be used in your Blade template:

@if($e->quote)
    {{ $e->quote->title }}
    {{ $e->quote_id }}
@endif

If you continue to use hasMany() instead of hasOne() (for whatever reason), then quote() will return an array of quote objects that you can loop through.

@foreach($e->quote as $q)
    {{ $q->title }}
@endforeach
Sign up to request clarification or add additional context in comments.

Comments

1

You need to wrap the quote->title in an if condition that checks if the quote exists.

If the quote for the expense is null(ie doesn't exist), then it can't have a title!

And also change your relationship to belongsTo. A quote has many expenses, and an expense belongs to a single quote if I understand correctly

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.