samedi 8 juin 2019

Laravel Backpack on delete cascade user and company doesn't work

I use a backpack cms build in Laravel. I have 3 tables. users, companies and company_user. All with migrations. So the problem is when i delete a user, the pivot table removes the record but not the company(ies) and other way around.

What do i do wrong?

How can achieve this?

User.php:

public function companies()
{
    return $this->belongsToMany('App\Models\Company', 'company_user', 'company_id', 'user_id');
}

Company.php

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

User migration:

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->engine = "InnoDB";
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });
}

Company migration:

public function up()
{
    Schema::create('companies', function (Blueprint $table) {
        $table->engine = "InnoDB";
        $table->increments('id');
        $table->string('companyname');
        $table->string('address');
        $table->integer('housenumber');
        $table->string('postalcode');
        $table->string('city');
        $table->string('province');
        $table->string('email');
        $table->string('phonenumber');
        $table->timestamps();
    });
}

Pivot company_user

public function up()
{
    Schema::create('company_user', function (Blueprint $table) {
        $table->engine = "InnoDB";
        $table->integer('company_id')->unsigned();
        $table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
        $table->integer('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    });
}

CompanyCrudController.php:

    $this->crud->addField([       // SelectMultiple = n-n relationship (with pivot table)
        'label' => "Tags",
        'type' => 'select_multiple',
        'name' => 'users', // the method that defines the relationship in your Model
        'entity' => 'users', // the method that defines the relationship in your Model
        'attribute' => 'name', // foreign key attribute that is shown to user
        'model' => "App\User", // foreign key model
        'pivot' => true, // on create&update, do you need to add/delete pivot table entries?

        // optional
        'options'   => (function ($query) {
            return $query->orderBy('name', 'ASC')->get();
        }), // force the related options to be a custom query, instead of all(); you can use this to filter the results show in the select
    ]);



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire