title: Laravel getting value from another table using eloquent
body: <p>I got tables like this:</p>
  <p>User table:</p>
  <pre><code>+----+---------+------------+
  | id |  name   |    level   |
  +----+---------+------------+
  |  1 |  user 1 |     1      |
  |  2 |  user 2 |     2      |
  +----+---------+------------+
  </code></pre>
  <p>Category table:</p>
  <pre><code>+----+---------+------------+
  | id | user_id |    name    |
  +----+---------+------------+
  |  1 |       1 | category 1 |
  |  2 |       2 | category 2 |
  |  3 |       2 | category 3 |
  +----+---------+------------+
  </code></pre>
  <p>Product table:</p>
  <pre><code>+----+-------------+------------+
  | id | category_id |    name    |
  +----+-------------+------------+
  |  1 |       1     | product 1  |
  |  2 |       2     | product 2  |
  |  3 |       3     | product 3  |
  |  4 |       3     | product 4  |
  +----+-------------+------------+
  </code></pre>
  <p>I want to get all the product with user_id = 2 through eloquent, and i got it through the code below:</p>
  <pre><code>$id = 2;
  $data = product::whereHas('category',  function ($q) use ($id) {
      $q-&gt;where('user_id', $id);
  })-&gt;get();
  </code></pre>
  <p>But when i want to print the category name and user name through $data, it doesnt seem to work, my code is like this:</p>
  <pre><code>$data-&gt;first()-&gt;category-&gt;name;
  $data-&gt;first()-&gt;user-&gt;name;
  </code></pre>
  <p>I can just solve this question with normal query build with JOIN, just join 3 tables together and select the desire columns and it's good to go, but i want to solve it with eloquent, i'm kinda clueless how to make it work.</p>
  <p>And i have another question, i got a query builder code like this:</p>
  <pre><code>    $id = false;
      if(auth()-&gt;user()-&gt;level != 1){
          $id = auth()-&gt;user()-&gt;id;
      }
      $data = DB::table('product')
                  -&gt;select('product.*', 'category.name AS category_name', 'users.name AS user_name')
                  -&gt;join('category', 'category.id', '=', 'product.category_id')
                  -&gt;join('users', 'users.id', '=', 'category.user_id')
                  -&gt;when($id, function($query, $id){
                      return $query-&gt;where('users.id', $id);
                  })
                  -&gt;get();
  </code></pre>
  <p>The idea of this code is when user level = 1, i will get all the products, but when user level != 1, i will get all the products with the user id = $id, the question is: how can i convert this to eloquent? I got an answer for myself but i think it's not good enough.</p>
  <p>Thanks.</p>