Answer the question
In order to leave comments, you need to log in
Many-to-Many returns Null, how to fix?
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');
}
}
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');
}
}
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
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question