Home > database >  Laravel Many-to-Many relationship not working
Laravel Many-to-Many relationship not working

Time:10-22

I'm facing a strange problem with Laravel Relations.

I'd like to access an event with many users (works perfect).

<?php

$event_with_user = Event::with('registered_users')->where('id', 253)->get();
dd($event_with_user);

And I'd like to access a user with all connected events:

<?php

$user_with_event = User::with('registered_events')->where('id', 1)->get();
        dd($user_with_event);

Where I always receive this error:

Illuminate\Database\Eloquent\RelationNotFoundException "Call to undefined relationship [registered_events] on model [App\User]."

I've checked the relations multiple times, but can't find a mistake. Does anyone else had that issue?


My Models

User.php

<?php

namespace App;

use App\Event;
use App\UserType;
use App\EventUser;
use App\Department;
use App\Evaluation;
use App\UserLocation;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'fname', 'lname', 'email', 'password', 'phone', 'email_verified_at', 'admin', 'user_type_id', 'last_login_at', 'last_login_ip', 'user_location_id', 'user_notification_type_id', 'user_notification_setting_id', 'slack_user_id', 'joinpoints_user_id'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function registered_events() 
    {
        return $this->belongsToMany(Event::class, 'event_user', 'event_id', 'user_id'); 
    }


}

Event.php

<?php

namespace App;

use App\User;
use App\EventRoom;
use App\EventType;
use App\EventStatus;
use App\EventLocation;
use App\EventParticipant;
use App\EventParticipantItems;
use Illuminate\Database\Eloquent\Model;
use Cviebrock\EloquentSluggable\Sluggable;

class Event extends Model
{
    use Sluggable;

    protected $fillable = [
        'event_type_id', 'user_id', 'status', 'customer', 'slug', 'datetime', 'duration','embed_chat','number_of_participants','heading', 'description_1', 'description_2', 'livestream_link', 'logo_link', 'event_password', 'participants_per_room', 'youtube_id', 'embed_code', 'session_link', 'hide_breakout', 'help_link', 'lang', 'layout', 'btn2_text', 'btn2_link', 'help_text', 'background_url', 'black_font',
    ];

    protected $dates = ['datetime'];

    public function getRouteKeyName()
    {
        return 'slug';
    }

    /**
     * Return the sluggable configuration array for this model.
     *
     * @return array
     */
    public function sluggable()
    {
        return [
            'slug' => [
                'source' => 'customer'
            ]
        ];
    }

    public function registered_users() 
    {
        return $this->belongsToMany(User::class, 'event_user', 'user_id', 'event_id')->withPivot('id', 'user_status', 'eventmanager', 'created_at', 'updated_at');
    }

  
}

My Tables:

  • user: id,....
  • event: id,...
  • event_user: id, user_id, event_id,...

CodePudding user response:

Look a bit closer at your models :

return $this->belongsToMany(Event::class, 'event_user', 'event_id', 'user_id'); 

and

return $this->belongsToMany(User::class, 'event_user', 'event_id', 'user_id');

Whilst the table is right, you will need to swap the order of event_id and user_id on one of them...

CodePudding user response:

Looks like you swapped the (foreign) keys:

In User.php:

public function registered_events() 
{
    return $this->belongsToMany(Event::class, 'event_user', 'user_id', 'event_id'); 
}

In Event.php:

public function registered_users() 
{
    return $this->belongsToMany(User::class, 'event_user', 'event_id', 'user_id')->withPivot('id', 'user_status', 'eventmanager', 'created_at', 'updated_at');
}

As you follow the correct Laravel database structure, you could simply put return $this->belongsToMany(Event::class); in User.php and return $this->belongsToMany(User::class)->withPivot(...); in Event.php

  • Related