Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Heimdall's avatar

belong to many

Hi

i have 3 table :

the table user :


    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('firstname');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->string('categorie_user');
            $table->string('droit');
            $table->string('phone');
            $table->string('blocked');
            $table->date('date_evenement');
            $table->rememberToken();
            $table->timestamps();

        });
    }

the table evenement :


    public function up()
    {
        Schema::create('evenements', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('categorie_id');
    $table->string('categorie_user');
    $table->string('name');
    $table->string('description');
    $table->string('ville');
    $table->string('rue');
    $table->date('date_evenement');
     $table->string('heure');
     $table->mediumText('image')->nullable();
    $table->timestamps();
        });
    }


and the table participant:

public function up()
{
    Schema::create('participants', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id');
$table->integer('evenement_id');
$table->timestamps();
    });
}

When a user subscribe at an event i save his id and the id of event of my table participant.

But after i want display the event whitch the user as subscribe. So i need to use belong to many. So i add this :

class User extends Authenticatable
{
    
            public function evenements()
    {
        return $this->belongsToMany('App\Evenement');
    }

}

and this :

class Evenement extends Model
{
        public function users()
    {
        return $this->belongsToMany('App\Users');
    }
}

but how display the event information ??

Ty

0 likes
19 replies
Heimdall's avatar

ok i change my class.

But on my controller i add what ?

and i dont understand that : $evenements = $user->comments;

Snapey's avatar

your participants table is acting as a pivot between participants and users.

However, there are some changes you should make

public function up()
{
    Schema::create('participants', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('user_id');
        $table->unsignedBigInteger('evenement_id');
        $table->timestamps();
    });
}

because your primary keys are bigIncrements, your foreign keys should be unsignedBigInteger to match

Then in your models, you are correct with a belongsToMany relationship (same in both models)

Because you don't follow the convention for pivot table naming, you must specify the name of the table.

class User extends Authenticatable
{
    
            public function evenements()
    {
        return $this->belongsToMany('App\Evenement', 'participants');
    }

}
Heimdall's avatar

@snapey yes i see the convention for pivot table to late ...

Ye i think my table participants is active, but idk how use it on my controller ?


       public function index()
    {
        return view('user/eventuser.index');
    }      

Snapey's avatar

Alternatively, you can use participants as a 'Pivot model'

https://laravel.com/docs/6.x/eloquent-relationships#defining-custom-intermediate-table-models

This is where your pivot is to be used as its own model as well as the link between two other models. The approach is slightly different. Still make the changes to the table columns as suggested, but change the models as;

class User extends Authenticatable
{
    
    public function evenements()
    {
        return $this->belongsToMany('App\Evenement')->using('App\Participant');
    }

}

and

class Evenement extends Model
{
    public function users()
    {
        return $this->belongsToMany('App\Users')->using('App\Participant');
    }
}

then specify your pivot model - extending Pivot instead of Model

class Participant extends Pivot
{
    //
}
Snapey's avatar

In both cases, you can you can find users events as

$user->load('evenements');

and then in blade

@foreach($user->evenements as $evenement)
    {{ $evenement->name }}
@endif
Heimdall's avatar

ok ty for your reply, i have change all my class, add the foreach on my view, and this on my controller:

       public function index()
    {
        $user->load('evenements');
        return view('user/eventuser.index',
        ['evenements' => $user]
    );

    }

but i have this error :

Undefined variable: user

Snapey's avatar

The evenements are children of $user. Just pass $user to view, after first initialising user.

    public function index()
    {
        $user = Auth::user();

        $user->load('evenements');

        return view('user/eventuser.index', compact('user'));

    }

You seem to be having problems with the basics. A trip to the Laravel From Scratch course is probably needed, as well as learning some php fundamentals.

Heimdall's avatar

oh yes sry i tired today.. and yes i will see laravel from scratch, i m again begginer :/

i think we have a problem with the pivot, bc i have this error :

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'projet-tutore.evenement_user' doesn't exist (SQL: select evenements.*, evenement_user.user_id as pivot_user_id, evenement_user.evenement_id as pivot_evenement_id from evenements inner join evenement_user on evenements.id = evenement_user.evenement_id where evenement_user.user_id in (2))

@snapey

Snapey's avatar

show your models now that you have modified them

Heimdall's avatar

ok:


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Evenement extends Model
{
    public function users()
    {
        return $this->belongsToMany('App\Users')->using('App\Participant');
    }
}



    public function evenements()
    {
        return $this->belongsToMany('App\Evenement')->using('App\Participant');
    }

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Participant extends Pivot
{
    //
}

@snapey

Snapey's avatar

Not sure why its not throwing a different error.

Your Participant model needs to specify where Pivot comes from by adding

use Illuminate\Database\Eloquent\Relations\Pivot;

at the top of the file.

Htin-Lynn's avatar
Level 1
public function index() 
{
  $user = User::with('evenements')->find(auth()->user()->id);
  return view('user.eventuser.index',compact('user'));
}

At Blade

@foreach($user->evenements as $evenement)

    <h1>{{ evenement->name }}</h1>
    <p>{{ evenement->description }}</p>

@endforeach
Heimdall's avatar

@htin-lynn with your code i have the same error

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'projet-tutore.evenement_user' doesn't exist (SQL: select evenements.*, evenement_user.user_id as pivot_user_id, evenement_user.evenement_id as pivot_evenement_id from evenements inner join evenement_user on evenements.id = evenement_user.evenement_id where evenement_user.user_id in (2))

Heimdall's avatar

i try this ;


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Participant extends Model
{
    //
}


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Evenement extends Model
{
        public function users()
    {
        return $this->hasMany('App\Users');
    }
}

<?php

namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{


            public function evenements()
    {
        return $this->belongsToMany('App\Evenement', 'participants');
    }
}

and on my controller :

public function index() 
{
  $user = User::with('evenements')->find(auth()->user()->id);

  dd($user);
  return view('user/eventuser.index',compact('user'));
}

and on my dd($user); i see that :

App\User {#329 ▼
  #guarded: []
  #hidden: array:2 [▶]
  #casts: array:1 [▼
    "email_verified_at" => "datetime"
  ]
  #connection: "mysql"
  #table: "users"
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:14 [▶]
  #original: array:14 [▶]
  #changes: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: array:1 [▼
    "evenements" => Illuminate\Database\Eloquent\Collection {#336 ▼
      #items: array:4 [▼
        0 => App\Evenement {#339 ▶}
        1 => App\Evenement {#342 ▶}
        2 => App\Evenement {#343 ▶}
        3 => App\Evenement {#344 ▶}
      ]
    }
  ]
  #touches: []
  +timestamps: true
  #visible: []
  #fillable: []
  #rememberTokenName: "remember_token"
}

so i have the good relation, but idk how display on my view the relation

(

#relations: array:1 [▼
    "evenements" => Illuminate\Database\Eloquent\Collection {#336 ▼
      #items: array:4 [▼
        0 => App\Evenement {#339 ▶}
        1 => App\Evenement {#342 ▶}
        2 => App\Evenement {#343 ▶}
        3 => App\Evenement {#344 ▶}
      ]

)

Snapey's avatar

It should be as I posted earlier

@foreach($user->evenements as $evenement)
    {{ $evenement->name }}
@endif 

Heimdall's avatar

ye ye i find it this after my message sry

That work good now

Ty all for your help

Please or to participate in this conversation.