spacemonkey
spacemonkey

Reputation: 2550

laravel insert date issuing an exception

I am attempting to simply insert a date into database table field and it is throwing me an error. The error shown is

ErrorException
Object of class DateTime could not be converted to string

The code for controller is:

.....

    $date = new DateTime('2000-01-01');
.....
$userModel->createUserAccount($email, $username, $password, $firstName, $lastName, $activationToken, $date);

and in the model (which i think causing the error):

public function createUserAccount($email, $username, $password, $firstName, $lastName, $activationToken, $randomDate)
    {
        /*This function will handle creating the new account for the guest*/

        DB::table('users')->insert(
            array('email' => $email, 'username' => $username, 'password'=> md5($password), 'first_name'=>$firstName, 'last_name'=>$lastName, 'activation'=>0, 'activation_token'=>$activationToken, 'session_token'=>null, 'ceated_on'=>$randomDate, 'last_updated'=>$randomDate));

    }

I would appreciate any possible support

Upvotes: 0

Views: 328

Answers (2)

Oli Folkerd
Oli Folkerd

Reputation: 8398

Following on from what @kajetons answered, if you create a mutator function in the users model then you can take a date of any specified format and convert it an approfpriate format for your database, this will then happen for you automatically and you wont need to do it each time.

in this case:

public function setLastUpdatedAttribute($value)
{
  if($value != ""){
    $this->attributes['last_updated'] = Carbon::createFromFormat('d/m/Y', $value)->toDateString();
  }
}

Upvotes: 1

kajetons
kajetons

Reputation: 4580

You have to format the DateTime object to insert it's value in the database:

$date = (new DateTime('2000-01-01'))->format('Y-m-d');

or:

$date = (new DateTime('2000-01-01'))->format('Y-m-d H:i:s');

The second option is a bit redundant in this case (since you didn't specify the time in your example), but the time should probably be used if you're replacing the default timestamps with your own custom solution.

However, a better option is using the Carbon class that is a part of Laravel, since it's a lot more convenient:

$date = Carbon::create(2000, 1, 1);

Upvotes: 1

Related Questions