nenads
2 years ago

Find results for specified user if they exists

Posted 2 years ago by nenads

Hi to all,

I have three tables in my database: users, tests and test_user. One user can have many tests, and one test can have many users.

I want to show list of all tests (even if user didn't do any test) and results for specified user if any record exist in pivot table.

class User extends Model
{
  public function tests()
  {
    return $this->belongsToMany(Test::class);
  }
}

class Test extends Model
{
  public function users()
  {
    return $this->belongsToMany(User::class);
  }
}

class TestController extends Controller
{
  public function index(User $user)
  {
    $tests = Test::with(['users' => function($query) use($user) {
      $query->where('users.id', $user->id);
    }])->get();

    return $tests;
  }
}

Index method in TestController works find but now a have $tests->users (plural) even if I have only one user and I don't like it.

@foreach($tests as $test)
  Name: {{ $test->name }}<hr>
  @foreach($test->users as $user)
    Date: {{ $user->pivot->created_at }}<br>
  @endforeach 
@endforeach 

Is there any better way to do this?

Thanks!

Please sign in or create an account to participate in this conversation.