3

I would like to create a model: FormsUser and the migration: forms_user

To use the table as a pivot because I have problems when I create a forms I am told that the table: 'forms_users does not exist' because I created the migration separately and when I go to my group members management page I get the error: 'forms_users does not exist' because here I have to use a pivot table so it must have this table name...

Can you help me to solve this problem or suggest an alternative? in short I want to create a forms and I create a team where I can add other user to the same forms.

migration: forms && Models Forms :

class Forms extends Model
{
    use HasFactory;
    use SoftDeletes;

    protected $fillable = [
        'title',
        'description',
        'date',
        'color',
        'progress',
        'user_id',
        'groupe_id',
        'formulaire',
        'logo',
    ];

    protected $dates = [
        'created_at',
        'deleted_at',
        'started_at',
        'update_at'
    ];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function usersGroupe()
    {
        return $this->belongsToMany(User::class);
    }
}

migration: users && Models User:

class User extends Authenticatable
{
    use HasApiTokens;
    use HasFactory;
    use HasProfilePhoto;
    use Notifiable;
    use TwoFactorAuthenticatable;
    use SoftDeletes;

    /**
     * The attributes that are mass assignable.
     *
     * @var string[]
     */
    protected $fillable = [
        'lastname',
        'firstname',
        'email',
        'password',
        'current_team_id',
        'profile_photo_path',
        'role_id',
    ];

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

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

    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = [
        'profile_photo_url',
        'role_id',
    ];

    protected $dates = [
        'created_at',
        'deleted_at',
        'started_at',
        'update_at'
    ];

    public function forms()
    {
        return $this->hasMany(Forms::class);
    }

    public function formGroupe()
    {
        return $this->belongsToMany(Forms::class);
    }

    public function role()
    {
        //return $this->hasMany(Role::class, 'id', 'role_id');
        return $this->hasOne(Role::class, 'id', 'role_id');
    }

    public function user()
    {
        return $this->hasOne(User::class);
    }
}

migration: formuser && Models FormsUser :

class FormsUser extends Model
{
    use HasFactory;

    protected $fillable = [
        'forms_id',
        'user_id'
    ];
}

migration create_forms_user :

Schema::create('forms_user', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
            $table->unsignedBigInteger('forms_id');
            $table->foreign('forms_id')->references('id')->on('forms');
            $table->unsignedBigInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users');
        });
Stack Realtek
  • 87
  • 1
  • 6

2 Answers2

3

So traditionally you don't have to create a pivot model. Laravel has some naming conventions that if you stick to will make things a bit easier. For example, Models should be singular but table names should be plural except for the pivot table. For example, your models should look like so:

class User extends Model { ... }

class Form extends Model { ... }

Then your table names would be :

users

forms

form_user

The pivot table should include the singular name of each table in alphabetical order. So F comes before U in the alphabet so it should read form_user.

Lastly in your Form model you would include a 'belongsToMany' function:

public function users() {
    return $this->belongsToMany('App\User');
}

and in the User Model you would include the same in reverse:

public function forms() {
    return $this->belongsToMany('App\Form');
}

If you entered the migrations correctly you will never need to create a pivot model. You can simply call the other objects through the relation to retrieve an array. ie:

$user->forms
$form->users
Dharman
  • 30,962
  • 25
  • 85
  • 135
  • my Model User looks like this: class User extends Authenticatable{...} because it was generated by Jetstream Livewire is this a problem? – Stack Realtek Dec 11 '21 at 20:09
  • No... the User class usually extends Authenticatable. If you follow the naming convention I explain above, you shouldn't need a pivot Model. – Dan Castanera Dec 11 '21 at 20:11
  • that's exactly what I did but I had an error telling me that I don't have a pivot table named forms_user when my migration had the same name but with an 's' character at the end – Stack Realtek Dec 11 '21 at 20:17
  • The pivot table in your migration should be the two class names in alphabetical order with an underscore in between. So yes... since you named your Forms class as plural then your pivot table in your migrations should be forms_user. – Dan Castanera Dec 11 '21 at 20:25
  • the error : SQLSTATE[42S02]: Base table or view not found: 1146 Table 'MyDB.forms_user' doesn't exist (SQL: select `users`.*, `forms_user`.`forms_id` as `pivot_forms_id`, `forms_user`.`user_id` as `pivot_user_id` from `users` inner join `forms_user` on `users`.`id` = `forms_user`.`user_id` where `forms_user`.`forms_id` = 31 and `users`.`deleted_at` is null) (View: /home/user/public_html/V8Form/resources/views/groupes/list.blade.php) – Stack Realtek Dec 11 '21 at 20:29
  • After looking at your updated question, it appears that your Forms model shouldn't need the 'user_id' if you use the relationship 'belongsToMany' which implies a pivot table. I would also take the 'belongsToMany' statement from your formGroupe function and move it to and replace the forms function in your User Model. – Dan Castanera Dec 11 '21 at 20:31
  • What do your migrations look like for the pivot table? – Dan Castanera Dec 11 '21 at 20:31
  • You can get rid of the 'id' and 'timestamps' from the pivot table since they are not needed. – Dan Castanera Dec 11 '21 at 20:38
  • Were you able to find the source of the problem? – Stack Realtek Dec 11 '21 at 21:07
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/240058/discussion-between-stack-realtek-and-dan-castanera). – Stack Realtek Dec 11 '21 at 21:07
0

After a lot of hard work I was finally able to solve the problem so instead of storing the data via the Models pivot I did it directly via a request to the migration.

Anyway, thanks for your participation. Problem solved!

Stack Realtek
  • 87
  • 1
  • 6