title: How to foreach a hasMany relationship in Laravel 6
body: <p>I'm using Laravel 6 and I want to foreach a hasMany relationship between Layanan Model and Objek Model</p>
  
  <p><strong>Layanan Model</strong></p>
  
  <pre class="lang-php prettyprint-override"><code>class Layanan extends Model
  {
      protected $fillable = ['nama_layanan'];
      protected $primaryKey = 'layanans_id';
  
      public function objeks()
      {
          return $this-&gt;hasMany(Objek::class);
      }
  }
  </code></pre>
  
  <p><strong>Objek Model</strong></p>
  
  <pre class="lang-php prettyprint-override"><code>class Objek extends Model
  {
      protected $fillable = ['layanan_id', 'tipe_objeks'];
      protected $primaryKey = 'objeks_id';
  
      public function layanan()
      {
          return $this-&gt;belongsTo(Layanan::class);
      }
  }
  </code></pre>
  
  <p><strong>Controller.php</strong></p>
  
  <pre class="lang-php prettyprint-override"><code>class ObjekController extends Controller
  {
      public function object()
      {
          $objek = \App\Objek::all();
  
          return view('pages.alat.object.object')-&gt;with('data', $objek);
      }
  }
  </code></pre>
  
  <p><strong>View</strong></p>
  
  <pre class="lang-php prettyprint-override"><code>@foreach ($data as $item)
      @foreach ($item-&gt;layanan as $layanan)
          &lt;tr&gt;
              &lt;td&gt;{!! $item-&gt;objeks_id !!}&lt;/td&gt;
              &lt;td&gt;{!! $layanan-&gt;layanan_id !!},&lt;/td&gt;
              &lt;td&gt;{!! $item-&gt;tipe_objeks !!}&lt;/td&gt;
              &lt;td&gt;{!! $item-&gt;created_at-&gt;format('d/m/Y') !!}&lt;/td&gt;
              &lt;td&gt;{!! $item-&gt;updated_at-&gt;format('d/m/Y') !!}&lt;/td&gt;
          &lt;/tr&gt;
      @endforeach
  @endforeach
  </code></pre>
  
  <p>I get the error</p>
  
  <blockquote>
    <p>Invalid argument supplied for foreach()</p>
  </blockquote>
  
  <p>What did I do wrong? Sometimes, it says that 'layanan' is non-object.</p>