@nenads Why not just $user->tests()->get() ?
Nov 4, 2017
8
Level 6
Find results for specified user if they exists
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!
Level 23
what i would do is
$tests = test::all();
$users = user::with('tests')->get()
then loop through the tests, do a check if users->test contain that & show it...
1 like
Please or to participate in this conversation.