title: How to get laravel relationship to work?
body: <p>Trying to learn how to get a role name from the role table by linking it to the user table with role_id in user table and user_id in the role table.</p>
  
  <p>below is what I've got, working through a couple of naming errors I've ended up here. </p>
  
  <p>How do I go about making this work?</p>
  
  <p>Works: Outputs '4'</p>
  
  <pre><code>{{ Auth::user()-&gt;role_id }}
  </code></pre>
  
  <p>Doesn't: Outputs nothing</p>
  
  <pre><code>{{ Auth::user()-&gt;role['name'] }}
  </code></pre>
  
  <p>Errors: Trying to get property of non-object (View: </p>
  
  <pre><code>{{ Auth::user()-&gt;role-&gt;name }}
  </code></pre>
  
  <p>relationships:</p>
  
  <pre><code>User model:
  
  public function roles()
  {
      return $this-&gt;hasOne('App\Role');
  }
  
  Role model:
  
  public function roles()
  {
      return $this-&gt;belongsToMany('App\User');
  }
  </code></pre>
  
  <p>Full Role class:</p>
  
  <pre><code>&lt;?php
  
  namespace Laravel;
  
  use Illuminate\Database\Eloquent\Model;
  
  class Role extends Model
  {
    //
  
  protected $fillable = [
      'name',
  ];
  
  public function users()
  {
      return $this-&gt;belongsToMany('App\User');
  }
  
  }
  </code></pre>