Reputation: 3592
I'm trying to access a relations table from a collection of data passed in from the controller. I am able to iterate the collection in my view but I am unable to access the relationship data.
There are 2 tables:
Controller:
public function getstock() {
return view('vehicles.getstock', ['stock' => \App\Stock::all()]);
}
Model (App\Stock) and then (App\StockData)
// From stock model:
public function stockdata() {
return $this->hasOne('App\StockData');
}
// Stock Data model:
public function stock() {
return $this->belongsTo('App\Stock');
}
View (loop):
@foreach ($stock as $k => $v)
{{ print_r($v->stockdata()->get())->year }}
@endforeach
When I try the query below, I get a
Undefined property: Illuminate\Database\Eloquent\Collection::$year (View: F:\websites\tempsite\resources\views\vehicles\getstock.blade.php)
However, year is a column in the stock_datas table.
I am also able to print_r data from the \App\StockData() table so the reference to the table is correct as doing print_r(\App\StockData::all()) from the controller does return all the rows as expected.
What am I doing wrong?
Upvotes: 1
Views: 2184
Reputation: 1731
First one You have to change {{ print_r($v->stockdata()->get())->year }}
this line, remove print_r. Next one in foreach loop you can do something like this
@foreach($stock as $one)
{{ $one->stockadata()->first()->year }}
@endforeach
For better solution you should check if isset $one->stockadata()->first()
and after that call ->year. Finally code should be like this
@foreach($stock as $one)
{{ isset($one->stockadata()->first()) : $one->stockadata()->first()->year : 'Default' }}
@endforeach
Upvotes: 1
Reputation: 2025
For example:
Stock.php model
class Stock extends Model
{
protected $primaryKey = 'id';
function stockdata() {
return $this->hasOne('App\StockDatas', 'id', 'stock_id');
}
public function getStock(){
return Stock::with('stockdata')->get();
}
}
In contriller
public function getstock(Stock $stock) {
return view('vehicles.getstock', ['stock' => $stock->getStock]);
}
view
@foreach ($stock as $k => $v)
{{ $v->stockdata->year }}
@endforeach
Upvotes: 0
Reputation: 163788
Since it's one to one relation, you should do it like this:
@foreach ($stock as $v)
{{ $v->stockdata->year }}
@endforeach
Upvotes: 1
Reputation: 5314
When calling get()
method on any relationship You will always receive collection, no matter what relationship You have.
There are at least two (2) ways to solve Your problem:
1. $v->stockdata->year
2. $v->stockdata()->first()->year
I would suggest You to use first one, because Your stockdata
has 1:1 relationship.
Good luck!
Upvotes: 0