Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Attempt to read property "users" on null #2535

Unanswered
eshbanbahadur asked this question in Q&A
Discussion options

I am trying to implement 'Many to Many' relationship in a default Laravel project but I only receive the following error:
"Attempt to read property "users" on null"

I even tried it with custom foreign keys but I did not get desired results and always get error message. I also know that this package not supports pivot tables for Many to Many relationships.

Please guide that how fix this issue

I have two models (user, role) and below is the code of my Models:

// USER MODEL


namespace App\Models;
use Jenssegers\Mongodb\Eloquent\Model;
class user extends Model
{
 // protected $connection = 'mongodb';
 protected $collection = 'users';
 public function roles(){
 return $this->belongsToMany(role::class,null,'role_id_custom');
 }
}

This is for ROLE Model

<?php
namespace App\Models;
#use Illuminate\Database\Eloquent\Factories\HasFactory;
#use Illuminate\Database\Eloquent\Model;
use Jenssegers\Mongodb\Eloquent\Model;
class role extends Model
{
 // protected $connection = 'mongodb';
 protected $collection = 'roles';
 public function users(){
 return $this->belongsToMany(user::class,null);
 }
}

And this is the code of Home Controller:

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\user;
use App\Models\role;
class home extends Controller
{
 public function index()
 {
 $role = user::find(1)->roles;
 return $role;
 // $user = role::find(1)->users;
 //return $user;
 }
 //
}

Here is the Schema of my MongoDB

USERS
_id:
name:
role_id_custom: (This is a foreign key)
ROLES
_id:
role:
role_id_custom

Please guide where is the issue

Thanks

You must be logged in to vote

Replies: 0 comments

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
1 participant

AltStyle によって変換されたページ (->オリジナル) /