User model:
namespace App\Models;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\Models\Tests\test as Test;
class User extends Authenticatable
{
public function viewedTests()
{
return $this->belongsToMany(Test::class, 'tests_views', 'user_id', 'test_id');
}
}
test model:
namespace App\Models\Tests;
use Illuminate\Database\Eloquent\Model;
use App\Models\User;
class test extends Model
{
public function usersViewed()
{
return $this->belongsToMany(User::class, 'tests_views', 'test_id', 'user_id');
}
}
relation table:
Schema::create('tests_views', function (Blueprint $table) {
$table->bigInteger('user_id');
$table->bigInteger('test_id');
$table->timestamps();
});
В качестве теста:
@foreach($test->usersViewed as $user)
<p>{{ $user->name }}</p>
endforeach