A
A
Artem2021-06-16 15:03:26
Laravel
Artem, 2021-06-16 15:03:26

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');
    }
}

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();
        });

As a test:
@foreach($test->usersViewed as $user)
       <p>{{ $user->name }}</p>
endforeach

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jazzus, 2021-06-16
@artem_atlas

Moreover, the connection is successfully created

The entry must be in an intermediate table. For mm, the attach method is used , not create.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question