Home > front end >  Laravel 8 : How to create a Pivot Model with its associated migration?
Laravel 8 : How to create a Pivot Model with its associated migration?

Time:12-12

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

CodePudding user response:

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

CodePudding user response:

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!

  • Related