SQLSTATE [23000]: Integrity constraint violation: 1452 Can not add or update a child row: a foreign key constraint fails

0

I am starting an application and it gives this error when I run the store method

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails ('laravel_apirestfull'.'vehiculos', CONSTRAINT 'vehiculos_fabricantes_id_foreign' FOREIGN KEY ('fabricantes_id') REFERENCES 'fabricantes' ('id') ON DELETE CASCADE ON UPDATE CASCADE) (SQL: insert into 'vehiculos' ('updated_at', 'created_at') values (2017-02-10 11:50:30, 2017-02-10 11:50:30))

MY MIGRATIONS UNTIL NOW

VEHICLES

  class CreateVehiculosTable extends Migration {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            Schema::create('vehiculos',function(Blueprint $table){

                $table->increments('id');
                $table->string('color');
                $table->float('cilindraje');
                $table->integer('potencia');
                $table->float('peso');
                  $table->timestamps();  

                $table->integer('fabricantes_id')->unsigned();
                $table->foreign('fabricantes_id')->references('id')->on('fabricantes')->onDelete('cascade')->onUpdate('cascade');

            });
        }

        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
           Schema::drop('vehiculos');
        } }

MANUFACTURERS

  class CreateFabricantesTable extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {

                Schema::create('fabricantes', function (Blueprint $table) {
                $table->increments('id');
                $table->string('nombre');
                 $table->string('telefono');
                $table->timestamps();
            });
        }

        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            Schema::drop('fabricantes');
        }
    }

VEHICLE MODEL

namespace App\modelos;

use Illuminate\Database\Eloquent\Model;

class vehiculo extends Model
{
  protected  $table = 'vehiculos';

  protected  $fillable = ['color','cilindraje','potencia','peso','fabricantes_id'];

  protected $hidden = ['created_at','updated_at'];

   public function fabricante()
   {
     return $this->BelongsTo('\App\modelos\fabricante');
   }
}

MANUFACTURER MODEL

class fabricante extends Model
{
   protected $table = 'fabricantes';

   protected $fillable = ['nombre','telefono'];

   protected $hidden = ['created_at','updated_at'];

    public function vehiculos()
   {
     return $this->hasMany('\App\modelos\vehiculo','fabricantes_id');
   }
}

CONTROLLER, METHOD STORE

public function store(Request $request)
    {
        if(!$request->color or !$request->cilindraje or !$request->potencia or !$request->peso):
            return response()->Json(['Notificacion ' => 'Todos los datos son obligatorios, por favor introducelos'],422);
        endif;

        vehiculo::create([$request->all()]);
          return response()->Json(['Notificacion ' => 'Vehiculo creado correctamente'],200);
    }

DATABASE SEEDER

  public function run()
    {

        $this->call(fabricantesseeder::class);
        $this->call(vehiculosseeder::class);
    }

I can not explain why it can give the fault, the relation is correct the id field that I try to enter in the field manufacturer_id exists in the table vehicles as id.

Any ideas?

    
asked by KurodoAkabane 10.02.2017 в 13:54
source

1 answer

1

The error is in the store method.

public function store(Request $request)
{
    if(!$request->color or !$request->cilindraje or !$request->potencia or !$request->peso):
        return response()->Json(['Notificacion ' => 'Todos los datos son obligatorios, por favor introducelos'],422);
    endif;

    vehiculo::create([$request->all()]);
      return response()->Json(['Notificacion ' => 'Vehiculo creado correctamente'],200);
}

Specifically in this part:

vehiculo::create([$request->all()]);

The $request->all() method already returns an array. That is why the create method, which expects an array, incorrectly constructs the insert by not finding the fields defined in the property $fillable . At the end you are passing the create method something like this:

vehiculo::create([[...]]);

To fix it just delete the [] . It should look like this:

vehiculo::create($request->all());

Greetings!

    
answered by 10.02.2017 / 15:16
source