Hamza Qureshi
Hamza Qureshi

Reputation: 202

how does laravel eloquent model works?

in db Seller table and this table have seller_id and i have column paid and i want to get that data using model so consider in controller i use

$seller = User::all();

in User Model

public function benefits(){
     return $this->belongsTo('App\Seller' , 'seller_id');
}

in view

@foreach($sellers as $key => $seller)
    <td>{{ $seller->benefits->paid}}<\td>
@endforeach

but problem is that i am unable to get value from column paid in seller table my result is null how this query will work?

Upvotes: 0

Views: 73

Answers (1)

IGP
IGP

Reputation: 15879

  • There is no $sellers variable in your code.
  • $seller is a collection, not a single record.
  • Eager load benefits relationship to avoid making too many queries.
$sellers = User::with('benefits')->all();
@foreach ($sellers as $seller)
    <td>{{ $seller->benefits->paid }}<\td>
@endforeach

If seller_id is a column in the Seller model's table, then the benefits relationship in the User model is either hasOne or hasMany

// User Model
public function benefits()
{
    return $this->hasOne('App\Seller', 'seller_id');
}
// Seller Model
public function user()
{
    return $this->belongsTo('App\User', 'seller_id');
}

Upvotes: 1

Related Questions