Estou tendo um problema ao deletar dados associados no Laravel. Tenho as tabelas users, registros e tags.
Como podem ver a tabela users se conecta com registros, enquanto uma tabela pivot(registro_has_tags) conecta as tabelas registro e tags.
O problema ocorre quando eu tento apagar um user, já que eu também quero apagar os dados da tabela registros referente aquele usuário, porém, quando tento fazer isso recebo uma mensagem de erro por conta da associação muitos para muitos entre tags e registros.
não faço ideia de como posso resolver isso no Laravel
Definição dos models:
User...
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Authenticatable implements JWTSubject
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* 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 registro()
{
return $this->hasMany(Registro::class); //User tem muitos registros
}
public function getJWTIdentifier()
{
return $this->getKey();
}
public function getJWTCustomClaims()
{
return [];
}
Registros...
namespace App;
use Illuminate\Database\Eloquent\Model;
class Registro extends Model
{
protected $fillable = [
'user_id',
'descricao',
'data_vencimento',
'valor',
'tipo',
'status'
];
public function user()
{
// Retorna a associação com base no objeto
return $this->belongsTo(User::class); //Perternce ao objeto usuário
}
public function tags()
{
return $this->belongsToMany(Tag::class, 'registros_has_tags');
}
}
Tags...
namespace App;
use Illuminate\Database\Eloquent\Model;
class Tag extends Model
{
protected $fillable = [
'nome',
'descricao'
];
public function registro()
{
return $this->belongsToMany(Registro::class, 'registros_has_tags');
}
}
Tentei realizar a operação pegando o id do user
public function destroy($id)
{
try{
$user = $this->user->findOrFail($id);
$user->registro()->detach();
$user->delete($id);
return response()->json([
'data'=> [
'msg'=> 'Usuário deletado com sucesso!'
]
], 200);
}catch(\Exception $e){
return response()->json(['erro: ' => $e->getMessage()], 401);
}
}
As migrations da api são:
users...
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
Registros...
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTableRegistros extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('registros', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->text('descricao');
$table->date('data_vencimento');
$table->float('valor');
$table->enum('tipo', ['D', 'C', 'P', 'R']);
$table->boolean('status')->nullable(true); //Campo pode ser nulo
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('registros');
}
}
Tags...
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTableTags extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('tags', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('nome');
$table->string('descricao');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('tags');
}
}
Tabela pivot(registros_has_tags)
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTableRegistrosHasTags extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('registros_has_tags', function (Blueprint $table) {
$table->unsignedBigInteger('registros_id');
$table->unsignedBigInteger('tags_id');
$table->foreign('registros_id')->references('id')->on('registros');
$table->foreign('tags_id')->references('id')->on('tags');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('registros_has_tags');
}
}