laravel project storing data in database does not work

1.1k views Asked by At

I have a laravel project that is using a mysql database with a few tables.Lets start by showing you all my files that are being used.My problem is that when I try to create the 'Conseillere' into the database, I get error:

'SQLSTATE[HY000]: General error: 1364 Field 'date_anniversaire' doesn't have a default value (SQL: insert into `conseilleres` () values ())'

Plus I dont know if what I did REALLY save it properly in the database. Basically, The conseillere model only has 2 date, but also have nom,prenom,adresse and adresse_courriel. Nom and Prenom are in another table called Personne.Adresse and ville are in another table named Adresse.Adresse_courriel is in another table called Courriel. Conseillere has all these attributes but they are referenced/contained in other tables/models.Conseillere model only contain date_anniversaire and date_entree column.Conseillere is a Personne. I am going to include some files that are needed, but im not sure if it would need more to help solve my issue.

First the usercontroller function that store the Conseillere into the database:

public function store(){

    $input = Input::all();
    $unepersonne = Personne::create([]);
    $uncourriel = new Courriel;
    $adresse = new Adresse;
    $conseillere = Conseillere::create([]);

    $uncourriel->adresse_courriel = $input['adresse_courriel'];
    $unepersonne->nom = $input['nom'];
    $unepersonne->prenom = $input['prenom'];

    $adresse->adresse = $input['adresse'];
    $adresse->ville = $input['ville'];

    //the following function are creating drop downs to input a date. for translation purpose, annee=year  mois=months and jour=day
    $conseillere->date_anniversaire = ConseillereController::construire_date($input['annee_anniversaire']-1, $input['mois_anniversaire']-1, $input['jour_anniversaire']-1);
    $conseillere->date_entree = ConseillereController::construire_date($input['annee_entree']-1, $input['mois_entree']-1, $input['jour_entree']-1);


    if ($unepersonne->save()){


    } else {

        return Redirect::back()->withInput()->withErrors($conseillere->validationMessages());
    }




}

construire_date function:

    private function construire_date($annee, $mois, $jour)
{
    if (checkdate($mois, $jour, $annee)) {
        $dateTest = new DateTime;
        $dateTest->setDate($annee, $mois, $jour);
        return $dateTest->format('Y-m-d');
    } else {
        return "invalide";
    }
}

}

Conseillere model:

<?php

namespace App\Models;

class Conseillere extends EloquentValidating {
protected $guarded = array('id');


public $timestamps = false;


public function conseillere() {
    return $this->belongsTo('App\Models\Conseillere');
}



protected $fillable = [
        'nom',
        'prenom',
        'adresse',
        'ville',
        'adresse_courriel',
        'date_anniversaire',
        'date_entree'
    ];

/**
 * Validation
 */

public $validationMessages;

public function validationRules() {
    return [
            'date_anniversaire' => 'nullable|date',
            'date_entree' => 'nullable|date'
    ];
}

}

Personne model:

<?php

namespace App\Models;

class Personne extends EloquentValidating
{

protected $table = 'personnes';


public $timestamps = false;

protected $fillable = [

    'nom', 
    'prenom',
];


public $validationMessages;

public function validationRules() {
    return
    [
            'personne' => 'required',
    ];
}


public function utilisateurs(){

    return $this->belongsToMany('App\Utilisateur');
}



public function adresse() {
    return $this->hasMany('App\Models\Adresse');
}


public function carte_credits(){

    return $this->belongsToMany('App\Carte_credit');
}

public function courriels(){
    return $this->hasMany('App\Models\Courriel');
}

}

Migrations of Conseillere:

    public function up()
{
    Schema::create('conseilleres', function (Blueprint $table) {

        $table->increments('id');
        $table->dateTime('date_anniversaire');
        $table->dateTime('date_entree');

        $table->integer('personne_id')
                        ->unsigned();
        $table->foreign('personne_id')
                        ->references('id')
                        ->on('personnes')
                        ->onDelete('cascade');

    });
}

Migrations of Personne:

    public function up()
{
    Schema::create('personnes', function (Blueprint $table) {
        $table->increments('id');
        $table->string('nom');
        $table->string('prenom');
        $table->timestamps();
    });
}

Ive been searching for a while and cant figure why the store function isnt working and not saving into the db.

2

There are 2 answers

10
Don't Panic On

Here's the line that is throwing the error you quote:

$conseillere = Conseillere::create([]);

The create method creates and saves a record immediately. It accepts an array of field => value data, but you are passing in an empty array, so it is trying to insert a blank record into the DB.

Going by your code, I think you are trying to create a new Conseillere model instance, set attributes, and then save it. If so, change that line to:

$conseillere = new Conseillere;

And then later, after you've set the required attributes:

$conseillere->date_entree = ...
$conseillere->save();

UPDATE

Note though that I think you are going to have additional problems as your migration shows that a record in conseilleres has a foreign key personne_id. So maybe you are trying to create your Personne, and save it along with the associated Conseillere? If yes, you need to make a few changes.

First, AFAICT your Conseillere <-> Personne relationship is not defined correctly. Your Conseillere model shows:

public function conseillere() {
    return $this->belongsTo('App\Models\Conseillere');
}

But why would Conseillere be related to itself? Shouldn't that be personne?

public function personne() {
    return $this->belongsTo('App\Models\Personne');
}

You will also need to add the inverse relation on your Personne model, I do not see it in your code.

Next, you need to save both the Personne, and the related Conseillere. You can do that as described in the docs:

// As above, change your create call to a simple 'new'
$conseillere = new Conseillere;

// ... rest of your code ...
$conseillere->date_entree = ...

// Now save the updated personne.  This only works bcs
// when you did $unepersonne = Personne::create([]) it created a 
// blank record in the DB with an id, basically you are doing an 
// update of an existing record here.
$unepersonne->save();

// Now save the related model.
$unepersonne->conseillere()->save($conseillere);
4
kunal On

If understand Your problem clearly or if you are using laravel 5.4 or 5.5... You need to open config/database.php here you need to change the value of strict to false. Something Like this:-

'mysql' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', 'localhost'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', 'forge'),
        'username' => env('DB_USERNAME', 'forge'),
        'password' => env('DB_PASSWORD', ''),
        'charset' => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix' => '',
        'strict' => false,  // replace true to false here
        'engine' => null,
    ],

Hope it helps!