Wolrab Wolrab - 4 months ago 16
SQL Question

Laravel Relationship

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?

Sam Sam
Answer

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