Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ozgunlu's avatar

Change Date Format using Mutator


namespace App;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;

class UserInformation extends Model {

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = "user_information";

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'title',
        'first_name',
        'last_name',
        'img_path',
        'born',
        'gender',
        'address',
        'country_id',
        'about',
        'institution',
        'area_of_expertise',
        'cv_path',
        'facebook',
        'twitter',
        'instagram',
        'linkedin',
        'university',
        'university_graduated_at',
        'md',
        'md_graduated_at',
        'associate_professor',
        'associate_professor_graduated_at'
    ];

    public function setBornAttribute($date) {
        $this->attributes['born'] = Carbon::createFromFormat('Y-m-d', $date);
    }

    public function users() {
        return $this->belongsTo('App\User', 'user_id', 'id');
    }
}

Error :

SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect date value: '26/10/1988' for column 'born' at row 1 (SQL: update user_information

How to update :

        $user = User::with('userInformation')->findOrFail($id);
        $user->update(array_filter($request->all()));
        $user->userInformation()->update(array_filter($request->only([
            'title',
            'first_name',
            'last_name',
            'img_path',
            'born',
            'gender',
            'address',
            'country_id',
            'about',
            'institution',
            'area_of_expertise',
            'cv_path',
            'facebook',
            'twitter',
            'instagram',
            'linkedin',
            'university',
            'university_graduated_at',
            'md',
            'md_graduated_at',
            'associate_professor',
            'associate_professor_graduated_at'
        ]), 'strlen'));

        return User::with('userInformation')->findOrFail($id);
    }

I send the born date d/m/Y format from user interface. When i store this data in mysql, i ve to reformat to Y-m-d..

I googled and found the mutators : https://laravel.com/docs/5.3/eloquent-mutators

I added setNameAttribute function to UserInformation model. And i refreshed the page then tried again. But nothing changed. I got the same error.

How can i fix this problem ?

p.s. : I am using Laravel 5.3

0 likes
22 replies
somnathsah's avatar

Defining date format for model can solve this issue. please try as below in your model.

protected $dateFormat = 'Y-m-d';
EventFellows's avatar

the error suggest that your $date varialbe has the different format ('26/10/1988') that hwat you defined in your createFromFormat method ('Y-m-d').

It seems you need to change one of these two so they match.

ozgunlu's avatar

@somnathsah i got an error when add that line :

InvalidArgumentException in Carbon.php line 582: Trailing data

I added before $fillable after $table variables.

ozgunlu's avatar

@EvenFellows i changed setBornAttribute function like that :

public function setBornAttribute($date) {
        $this->attributes['born'] = Carbon::createFromFormat('d/m/Y', $date)->format('Y-m-d');
   }

But when i debugged this code, that method not called..

TheBlueDragon's avatar

@ozgunlu hmmmm i have similar

and its work for me

public function setNextDateAttribute($input)
{
    if ($input != null && $input != '') {
        $this->attributes['next_date'] = Carbon::createFromFormat(config('app.date_format'), $input)->format('Y-m-d');
    } else {
        $this->attributes['next_date'] = null;
    }
}

check the format in config file otherwise replace it

but i think your method should work fine also !!

EventFellows's avatar

If you can, I would change it, but it all comes down to preference. Many people love to work with Carbon instances as they can be very convenient.

You can also make it work with date so that is a different topic. In your setup you essentially pass in the date as a string so you might get the mismatch form that data type.

ozgunlu's avatar

@EventFellows i changed to timestamp but i recognized, the problem is setBornAttribute not called from update method. I do not know why it not called.

sujancse's avatar

Why not are you change $this->attributes['born'] = Carbon::createFromFormat('Y-m-d', $date); to $this->attributes['born'] = Carbon::createFromFormat('d/m/Y', $date); this should work.

EventFellows's avatar

Are you using Eloquent? What happens if you comemnt out the born part of it? Does the rest get save to DB?

ozgunlu's avatar

@EventFellows i am sorry, but how can i understand ? I am new on Laravel. My get method calls the getBornAttribute but update method does not call setBornAttribute method.

That update method's namespace is : namespace Illuminate\Database\Eloquent;

@st8113 The problem is : setBornAttribute not called from my update method.

UPDATE:

Yes @EventFellows, it can patching. I dont have to send all inputs to update.

EventFellows's avatar

Are you sure it is really not called? try to put in a dd('whatever'); into your setBornAttrribute() and see if it really is not called.

What error are you getting? What born date ends up in the database?

ozgunlu's avatar

Whole error :

QueryException in Connection.php line 770: SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value: '15/07/1955' for column 'born' at row 1 (SQL: update user_information set first_name = Özgün, `last_na = ÜNLÜ, ?, ` = 15/07/1955, 5, `ge = 0, 0, `update = 2017-05-25 12:39:27 where re `user_informa.n`.`use = 1 and nd `user_informa.n`.`use is not null) in Connection.php line 770 at Connection->runQueryCallback('update te `user_informa set et `first_ = ?, ?, `last_ = ?, ?, ` = ?, ?, `ge = ?, ?, `update = ? where re `user_informa.n`.`use = ? and nd `user_informa.n`.`use is not null', array('Özgün', 'ÜNLÜ', '15/07/1955', '0', '2017-05-25 12:39:27', '1'), object(Closure)) in Connection.php line 726 at Connection->run('update update `user_inf set n` set `fi = ?, ` = ?, `l = ?, ` = = ?, ` = ?, = ?, ` = ?, `up = ? where where `user_inf.ation`. = ? and ? and `user_inf.ation`. is not null', array('Özgün', 'ÜNLÜ', '15/07/1955', '0', '2017-05-25 12:39:27', '1'), object(Closure)) in Connection.php line 508 at Connection->affectingStatement('update nt('update `user set ation` set = ?, name` = ? = ?, name = ?, born` = ?, nder` = ?, = ? where = ? where `user.formati = ? and d` = ? and `user.formati is not null', array('Özgün', 'ÜNLÜ', '15/07/1955', '0', '2017-05-25 12:39:27', '1')) in Connection.php line 447 at Connection->update('update update('update ` set formation` = ?, rst_name` = ?, ast_ = ?, ?, `bo = ?, `gender` = ? where _at` = ? where `.r_infor = ? and er_id` = ? and `.r_infor is not null', array('Özgün', 'ÜNLÜ', '15/07/1955', '0', '2017-05-25 12:39:27', '1')) in Builder.php line 2168 at Builder->update(array('first_name' => 'Özgün', 'last_name' => 'ÜNLÜ', 'born' => '15/07/1955', 'gender' => '0', 'updated_at' => '2017-05-25 12:39:27')) in Builder.php line 543 at Builder->update(array('first_name' => 'Özgün', 'last_name' => 'ÜNLÜ', 'born' => '15/07/1955', 'gender' => '0', 'updated_at' => '2017-05-25 12:39:27')) in HasOneOrMany.php line 360 at HasOneOrMany->update(array('first_name' => 'Özgün', 'last_name' => 'ÜNLÜ', 'born' => '15/07/1955', 'gender' => '0', 'updated_at' => '2017-05-25 12:39:27')) in UserService.php line 91 at UserService->updateUser(object(Request), '1') in UserController.php line 72 at UserController->update(object(Request), '1') at call_user_func_array(array(object(UserController), 'update'), array(object(Request), 'user' => '1')) in Controller.php line 55 at Controller->callAction('update', array(object(Request), 'user' => '1')) in ControllerDispatcher.php line 44 at ControllerDispatcher->dispatch(object(Route), object(UserController), 'update') in Route.php line 189 at Route->runController() in Route.php line 144 at Route->run(object(Request)) in Router.php line 653 at Router->Illuminate\Routing{closure}(object(Request)) in Pipeline.php line 53 at Pipeline->Illuminate\Routing{closure}(object(Request)) in SubstituteBindings.php line 41 at SubstituteBindings->handle(object(Request), object(Closure)) in Pipeline.php line 137 at Pipeline->Illuminate\Pipeline{closure}(object(Request)) in Pipeline.php line 33 at Pipeline->Illuminate\Routing{closure}(object(Request)) in ThrottleRequests.php line 49 at ThrottleRequests->handle(object(Request), object(Closure), '60', '1') in Pipeline.php line 137 at Pipeline->Illuminate\Pipeline{closure}(object(Request)) in Pipeline.php line 33 at Pipeline->Illuminate\Routing{closure}(object(Request)) in Pipeline.php line 104 at Pipeline->then(object(Closure)) in Router.php line 655 at Router->runRouteWithinStack(object(Route), object(Request)) in Router.php line 629 at Router->dispatchToRoute(object(Request)) in Router.php line 607 at Router->dispatch(object(Request)) in Kernel.php line 268 at Kernel->Illuminate\Foundation\Http{closure}(object(Request)) in Pipeline.php line 53 at Pipeline->Illuminate\Routing{closure}(object(Request)) in CheckForMaintenanceMode.php line 46 at CheckForMaintenanceMode->handle(object(Request), object(Closure)) in Pipeline.php line 137 at Pipeline->Illuminate\Pipeline{closure}(object(Request)) in Pipeline.php line 33 at Pipeline->Illuminate\Routing{closure}(object(Request)) in DetectRoute.php line 46 at DetectRoute->handle(object(Request), object(Closure)) in Pipeline.php line 137 at Pipeline->Illuminate\Pipeline{closure}(object(Request)) in Pipeline.php line 33 at Pipeline->Illuminate\Routing{closure}(object(Request)) in PreventRedirect.php line 17 at PreventRedirect->handle(object(Request), object(Closure)) in Pipeline.php line 137 at Pipeline->Illuminate\Pipeline{closure}(object(Request)) in Pipeline.php line 33 at Pipeline->Illuminate\Routing{closure}(object(Request)) in Pipeline.php line 104 at Pipeline->then(object(Closure)) in Kernel.php line 150 at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 117 at Kernel->handle(object(Request)) in index.php line 53 at require_once('C:\wamp\www\easypath_api\public\index.php') in server.php line 21

setBornAttribute not called... In database; born type is timestamp and NULL. Same as created_at and updated_at...

<?php

namespace App;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;

class UserInformation extends Model {

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = "user_information";

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'title',
        'first_name',
        'last_name',
        'img_path',
        'born',
        'gender',
        'address',
        'country_id',
        'about',
        'institution',
        'area_of_expertise',
        'cv_path',
        'facebook',
        'twitter',
        'instagram',
        'linkedin',
        'university',
        'university_graduated_at',
        'md',
        'md_graduated_at',
        'associate_professor',
        'associate_professor_graduated_at'
    ];

    public function getBornAttribute($date) {
        if (!empty($date))
            return Carbon::createFromFormat('Y-m-d', $date)->format('d/m/Y');
    }

    public function setBornAttribute($date) {
        dd('whatever');
        $this->attributes['born'] = Carbon::createFromFormat('d/m/Y', $date);
    }

    public function users() {
        return $this->belongsTo('App\User', 'user_id', 'id');
    }
}

And my all service :

namespace App\Services\v1;

use Validator;

use App\User;
use App\UserInformation;

class UserService {

public function updateUser($request, $id) {
        $user = User::with('userInformation')->findOrFail($id);
        $user->update(array_filter($request->all()));
        $user->userInformation()->update(array_filter($request->only([
            'title',
            'first_name',
            'last_name',
            'img_path',
            'born',
            'gender',
            'address',
            'country_id',
            'about',
            'institution',
            'area_of_expertise',
            'cv_path',
            'facebook',
            'twitter',
            'instagram',
            'linkedin',
            'university',
            'university_graduated_at',
            'md',
            'md_graduated_at',
            'associate_professor',
            'associate_professor_graduated_at'
        ]), 'strlen'));

        return User::with('userInformation')->findOrFail($id);
    }
}
sujancse's avatar

Hey @ozgunlu your problem is on your controllers update method. Could you please show me your update method.

1 like
ozgunlu's avatar

Here is my Controller update :

/**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id) {
        try {
            $user = $this->users->updateUser($request, $id);
            return response()->json($user, 200);
        } catch (ModelNotFoundException $ex) {
            throw $ex;
        } catch (Exception $e) {
            return response()->json(['message' => $e->getMessage()], 500);
        }
    }

And api route :

Route::resource('/v1/users', v1\UserController::class, [
    'except' => ['create', 'edit']
]);
abusalameh's avatar

@OZGUNLU at first define born in your model within $dates property

<?php 

class Model extends Eloquent {

protected $datas = ['born','created_at', 'updated_at'];


}

and do the Carbon formatting .. then you're ready to go on..

^^

ozgunlu's avatar

@st8113 thank you so much, it works...

I called $user->user_information()->update(........

But i deleted the paranthesis and write like $user->user_information->update(........

It printed the dd('whatever') to screen.

Thank you so much for perfect support @st8113 @EventFellows

2 likes
stefan s.'s avatar

    public function setBornAttribute($data) {
        $this->attributes['born'] = Carbon::parse($data)->format('Y-m-d');
    }

Please or to participate in this conversation.