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

EliasSoares's avatar

@jeffberry and @JarekTkaczyk, Thanks for your help. And everyone.

I didn't decided yet witch method to use, and I didn't know that $dates eloquent way to do.

My application is developed for a company that operates in Brazil and Italy, and may be operating in other countries futurely.

Let's supose that I wan't to create a user option to choice witch time format to use. Where can I set this choice as default format for that instance?

Should I do this at every model? Or there's a better place to define default date format?

protected function getDateFormat() {
    return Auth::user()->date_format;
}

@jeffberry Also, I understood why is better to don't use acessors and mutators in this case. Receiving the raw Carbon object is better to allow me using it methods in my application. Thanks for your advice! :)

MateusAzevedo's avatar

@eliaseas In this case, I think that a date picker will be the best option. This way you don't need to worry about date format, your form should aways send a valid one.

But if you want to let user decide, you can create a base model that overrides date format.

class BaseModel extends Eloquent {
    protected function getDateFormat() {
        return Auth::user()->date_format;
    }
}

// Then your models should extend that base model:
class User extends BaseModel {
    // All date should work with that format
}

Remember, this is not the best option in this case, since ALL dates will follow that format.

Jeffberry's avatar

Hey @eliaseas,

I'm glad you understand the benefits of using Eloquent's native API to handle your date fields! I'm glad you were able to read past @JarekTkaczyk's noise to get your solution too.

As for allowing your users to choose their own custom date format -- overriding the getDateFormat is definitely not the way to go as that's the format in which the dates get stored. All dates should be stored the same way. Instead what you would want to do is just format the date upon output based on the visitor's setting.

So we already know that by using Eloquent to handle your dates, you'll receive a Carbon instance back, so you can output your dates like this:

Date of Birth {{ $user->dob->format('m/d/Y') }}

So something like this will format the date based on the user's setting:

Date of Birth: {{ $user->dob->format(Auth::check() ? Auth::user()->date_format : 'm/d/Y') }}

If you do plan on having different date formats depending on which country, please do not follow the advice the others were giving you of using the accessors and mutators. The limitation they impose on you is they limit you to one valid format which you can supply to the model.

By not using the mutator, you can pass in a date of any format because you'll convert it to a standardized format before it hits the model.

Basically what I'm suggesting is the ability to do this:

$user->dob = Carbon::createFromFormat('Y-m-d', '1975-05-21'); // Country 1 in Y-m-d format
$user->dob = Carbon::createFromFormat('m/d/Y', '05/21/1975'); // Country 2 in m/d/Y format
$user->dob = Carbon::createFromFormat('m.d.y', '05.21.1975'); // Country 1 in m.d.y format

All three of those will pass Eloquent the same date, but you can see they were all input by the user in a different format. You won't have to do anything on the Eloquent side either because it will automagically handle them so long as you added dob to $dates

Good luck mate! Let me know if there's anything else we can help with.

1 like
JarekTkaczyk's avatar

OK, I was called again, but pff...

@eliaseas Choose the approach that suits you, that's all. Below is something for you to consider, and btw yes, use $dates handling provided by the Eloquent and skip the accessor.

Mutator, on the other hand, is completely different thing here and it's just making your work easier - if you want Eloquent do the job for you, then use it, otherwise you will have to take care of it:

// very basic controller as a sensible example, using mutator
public function store()
{
   // input validation
   // ...

   $user = User::create(Input::all());

   return Redirect::route('users.show', [$user->id]);
}

// vs no mutator
public function store()
{
   // input validation
   // ...

   $user = new User(Input::except('dob'));
   $user->dob = Carbon::createFromFormat(
      $u = Auth::user() 
        ? $u->format
        : 'd/m/Y', // here you asked fellow programmer about the default format, luckily he recalled ;)
                   // Now, really: controller is not the best place for placing business default values
                   // neither is a repository - that's what I think, make your own opinion
      Input::get('dob')
   )

   $user->save();

   return Redirect::route('users.show', [$user->id]);
}

The above obviously will work considering fillable / guarded attributes, but that's different story.

Now, there's also no problem with your requirement concerning different format. Let's stick to the previously mentioned per user setup:

public function setDobAttribute($value)
{
        // I suppose Eloquent model is much better place for storing default format
        // of course it might be retrieved from config, or wherever you like instead
        $format = ($u = Auth::user()) ? $u->format : 'd/m/Y';

        $this->attributes['dob'] = $this->fromDateTime(Carbon::createFromFormat($format, $value));
}

WIth this setup all you need in the example controller above is again:

public function store()
{
   // input validation, check the dob format according to the user/location
   // and don't worry about it no more, Eloquent will handle it for you

   $user = User::create(Input::all());

   return Redirect::route('users.show', [$user->id]);
}

That's what you can use mutator in your case.

Pretty much everything has been already said about outputting the date, so I'm not touching this topic again.

2 likes
colourmill's avatar

@Jeffberry, that is one low blow man and it's no way to behave to someone in person nor on the internet. It's straight up bullying and to be honest you're making my blood boil by resorting to these tactics.

Not to mention that @JarekTkaczyk was right by saying that your solution does not only not answer the question, it in fact misses the entire point of the problem, being that the date cannot be parsed automatically. It is only after this was pointed out to you, twice, that you address it. You only get to the crux of the issue in your third post. That's what @JarekTkaczyk tried to point out to you, but it seems that in your anger you kept missing it.

This isn't a contest however, you both had the best intentions, and I'm not here to decide on the "winner", I'm just saying that you have no reason to go on the attack and then try to set other people up against a person as if he isn't here and call his contribution "noise". That's just extremely childish.

1 like
Jeffberry's avatar

@colourmill I am not even interested in conversing with you about the topic. My solution both answered the question (it was chosen as the correct answer) as well as it addresses the problem including the problem we did not know he had where he may have different formats of dates that are going to be inputted.

Nothing needed to be pointed out to me any number of times for me to address it -- the point is a mutator is not needed and should not be used, as it limits the application on what can be inserted. Instead, the date should be standardized before it is sent to the model. There was no need for me to get to the crux of the issue in any of my posts -- because it was an issue that was being created by the poor answers that were given. There are four different ways to input a date into Eloquent -- I merely suggested that the user use one of these native ways as it will provide more flexibility. I hear that you are telling me that Jarek "pointed out to me that the date cannot be parsed automatically" however I have showed him the definition that it can be, which is what I was saying from the beginning. I even wrote an (unbiased) test which demonstrates such. There is no need for us to have this technical discussion again.

You also need to understand that I wasn't attacking, but rather I was on the defense. The attacks began with the other guy both in this thread and in the other unpleasant conversation I had with this guy. I did not address him in this conversation until he chose to trash my answer (again). The bottom line is, the answer he provided is limiting and unnecessary. Eloquent supports the functionality natively and he claims himself to be an Eloquent guru so I assume he knows that.

I did not get "angry" until he chose to insult me and play childish games with me in "running a test" which he very well knew was not even one of the methods I suggested. At that point, I was done being civil and he needs to understand that his attitude towards me is not appreciated (which I tried to politely tell him several times both in this topic and the other). In person I would have said the same words.

Bottom line is, it's not cool that you're harping on me about the discussion that was made here. It takes two to start a fire like this, and obviously my solution was appropriate for the original question as indicated by the highlighted green post at the top of the thread.

I'm here to converse and learn with fellow Laravelers. Please keep the attitude positive and keep a forward movement. It's absurd that I would have to so violently defend my answer from the attacks of another user.

To follow up on the actual topic, a mutator is still the wrong answer. In Jarek(?)'s last post he suggests that the format should be determined in the model:

public function setDobAttribute($value)
{
    $format = Auth::user() ? Auth::user()->date_format : 'd/m/Y';
    ...
}

The problem here is that different users can have different date formats. When a user edits his own profile he may have a day format of Y-m-d which would be used by the setDobAttribute method, but if an admin goes to edit the user's profile the admin may have a date format of m/d/y which would then be used by setDobAttribute. Both of these would be assuming that the date was being inputted in the same format as the visitor. Maybe he has a custom datepicker that does not go off the visitor's date format, and he needs to set the DOB based on that custom format -- that is why it would be more appropriate to have the date conversion in a Command, ServiceClass, or Controller. A mutator is simply the wrong answer and will not provide the dynamics that this user requires. A much better place would be to convert the date to a standardized format before sending it to Eloquent. That's just simply the right answer and is how the Eloquent API by definition is expecting the value.

Good day gentlemen.

JarekTkaczyk's avatar

@Jeffberry it's getting even better now. I suppose you know the OP's application better than himself, so many assumptions already..

Anyway, just like previously, all you're trying to do is to tell everyone around 'my way or the highway'. A mutator is simply the wrong answer..., That's just simply the right answer... blah blah blah

Wrong because of Auth::user(), that made my day! Yes, that was the most important part of this example, part that 100% depends on the business of the application which neither of us knows...

You didn't understand any of my posts here and missed the point of each one of them.

And this one:

Basically what I'm suggesting is the ability to do this:
$user->dob = Carbon::createFromFormat('Y-m-d', '1975-05-21'); // Country 1 in Y-m-d format
$user->dob = Carbon::createFromFormat('m/d/Y', '05/21/1975'); // Country 2 in m/d/Y format
$user->dob = Carbon::createFromFormat('m.d.y', '05.21.1975'); // Country 1 in m.d.y format

ability to do what? Manually parse that date in a controller (service, whatever). Yeah, you showed us all...

Jeffberry's avatar

@JarekTkaczyk I'm not saying I understand his application better than him, but I actually took the time to read his post in which he was excited about the idea of being able to use different date formats because of the possibility of his application using different date formats. He also stated he understood the limitations of a mutator and claimed himself that it may not fit his use-case.

A model should not be parsing data based on a user's setting. What if their is a background cron script in the background that goes and updates a bunch of things. I'm not saying this would ever happen in the case of birthdays, but just in general; depending on which user the cron fired under, a different format would be used for the update/mutator? Ha!

There is no reason for me to explain my logic to you any longer. By Eloquent's definition it is simply the right answer. My answer is using Eloquent natively and I am adding nothing whatsoever to the code, so how could I even be wrong?

Story over man. You know I'm not wrong, I may not be saying the same answer as you but you know I'm not wrong. You just obviously don't want to be civil with each other so you continue to egg it on. Please give it up, let's go back to being strangers, I really preferred it that way. You are a very unpleasant person.

Jeffberry's avatar

I'm just honestly not sure what it is about me that makes you seek me out and attack me in several threads now. Other people provided less-than-correct answers in this thread and breeze right past them, however as soon as I posted a correct answer you wanted to try and come up with every fallacy you could to depict it as wrong? Do you just get intimidated when there is another intelligent person in the room? Clearly you're no fool, and I imagine you are a pretty intelligent character; however your ability to converse and work with people is very lacking. The only conclusion I can come to is you fear other intelligent people. Programming is probably the wrong world for you then buddy.

Jeffberry's avatar

You must just enjoy being an antagonist. You refuse to have a conversation even when one is being civil. Your flaw not mine though. I'm going to go ahead and take my trophy and get out of here. See ya!

noblemfd's avatar

@eliassoares - How did you put you code in the Controller and View for this

public function getDobAttribute($value)
{
    return Carbon::parse($value)->format('d/m/Y');
}

public function setDobAttribute($value)
{
    $this->attributes['dob'] = Carbon::createFromFormat('d/m/Y', $value)->toDateString();
}

I have similar problem. See my code below:

Model

  protected $fillable = [
          'name',
          'start_date',
          'end_date',
      ];

protected $dates = [
   'start_date',
   'end_date'
  ];

Request Rules:

        'start_date.*' => [
            'required', 
            'date',
            'date_format:Y-m-d',
        ],
      
        'end_date.*' => [
            'required', 
            'date',
            'date_format:Y-m-d',
            'after:start_date.*'
        ], 

Controller

        foreach(Arr::wrap($request->activity) as $key => $activity){
            $startDate = Carbon::parse($request->start_date[$key]);
            $endDate = Carbon::parse($request->end_date[$key]);

            $goaldetail = new AppraisalGoalDetail();

             $goaldetail->start_date                 = $startDate ->toDateString();
             $goaldetail->end_date                   = $endDate->toDateString();                 
             $goaldetail->save();
 }

view:

  <td>
     <input type="date" name="start_date[]" placeholder="dd/mm/yyyy" class="form-control start_date" min="{{Carbon\Carbon::now()->firstOfYear()->format('Y-m-d')}}" max="{{Carbon\Carbon::now()->lastOfYear()->format('Y-m-d')}}">
  </td>

  <td>
     <input type="date" name="end_date[]" placeholder="dd/mm/yyyy" class="form-control end_date" min="{{Carbon\Carbon::now()->firstOfYear()->format('Y-m-d')}}" max="{{Carbon\Carbon::now()->lastOfYear()->format('Y-m-d')}}">
     </td>

When I submitted the form, I got this error:

[2020-06-26 09:16:52] production.ERROR: Exception: DateTime::__construct(): Failed to parse time string (2) at position 0 (2): Unexpected character in /var/www/html/laravelapp/vendor/nesbot/carbon/src/Carbon/Traits/Creator.php:81
Stack trace:
#0 /var/www/html/laravelapp/vendor/nesbot/carbon/src/Carbon/Traits/Creator.php(81): DateTime->__construct('2', Object(Carbon\CarbonTimeZone))
#1 /var/www/html/laravelapp/vendor/nesbot/carbon/src/Carbon/Traits/Creator.php(174): Carbon\Carbon->__construct('2', NULL)
#2 /var/www/html/laravelapp/vendor/nesbot/carbon/src/Carbon/Traits/Creator.php(201): Carbon\Carbon::rawParse('2', NULL)
#3 /var/www/html/laravelapp/app/Http/Controllers/AppraisalGoalsController.php(333): Carbon\Carbon::parse('2')
#4 [internal function]: App\Http\Controllers\Appraisal\AppraisalGoalsController->store(Object(App\Http\Requests\AppraisalGoal\StoreAppraisalGoalRequest))
#5 C:\xampp\htdocs\laravelapp\vendor\laravel\framework\src\Illuminate\Routing\Controller.php(54): call_user_func_array(Array, Array)
#6 C:\xampp\htdocs\laravelapp\vendor\laravel\framework\src\Illuminate\Routing\ControllerDispatcher.php(45): Illuminate\Routing\Controller->callAction('store', Array)

Thanks

Previous

Please or to participate in this conversation.