Laravel 5.3 access hasone in elequant from view -


i'm trying access relations table collection of data passed in controller. able iterate collection in view unable access relationship data.

there 2 tables:

  • stocks (default model)
  • stock_datas (has foreign key stock_id setup)

controller:

public function getstock() {         return view('vehicles.getstock', ['stock' => \app\stock::all()]);     } 

model (app\stock) , (app\stockdata)

// 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 $k => $v)      {{ print_r($v->stockdata()->get())->year }} @endforeach 

when try query below,

 undefined property: illuminate\database\eloquent\collection::$year (view: f:\websites\tempsite\resources\views\vehicles\getstock.blade.php) 

however, year column in stock_datas table.

i able print_r data \app\stockdata() table reference table correct doing print_r(\app\stockdata::all()) controller return rows expected.

what doing wrong?

first 1 have change {{ print_r($v->stockdata()->get())->year }} line, remove print_r. next 1 in foreach loop can

@foreach($stock $one)      {{ $one->stockadata()->first()->year }} @endforeach 

for better solution should check if isset $one->stockadata()->first() , after call ->year. code should this

@foreach($stock $one)  {{ isset($one->stockadata()->first()) : $one->stockadata()->first()->year : 'default' }} @endforeach 

Comments

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -