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

afrayedknot's avatar

Allowing custom date formats

So I'm running into an issue with my application - where users often enter "dates".

Currently my application allows 'd-m-Y' - but I need to allow 'm/d/Y' etc.

My thoughts are I can make this a configurable option for the user - and they state the date format in their config - and that is then used throughout the application. Something like this:

{{ $date->format(auth()->user()->date_format) }}

That would work for displays fairly well. But then I need to handle validation. Once again - I am thinking something like this in my FormRequest classes:

return [
            'date' => 'required|string|date|date_format:'.auth()->user()->date_format,
            'notes' => 'string|max:255',
        ];

So that way the validation is relative to the users setting.

However - it is the last bit that I'm stumped with. How do I then allow eloquent to safely store the date? Currently I do this with my fixed date format:

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

One option I could do is this:

public function setDateAttribute($value)
    {
        $this->attributes['date'] = Carbon::createFromFormat(auth()->user()->date_format, $value);
    }

...but I dont like the idea of putting auth() related functions into my Eloquent models - I know they dont belong there.

So how can I get around this? I need Eloquent to be "aware" of the date setting - so it stores the string correctly?

Is there a sanizitize option I could use somewhere before it hits Eloquent - so I could always send Eloquent a specific date format?

0 likes
5 replies
afrayedknot's avatar

But then I'm still calling the 'session' inside Eloquent? Seems like the same problem doesnt it?

bestmomo's avatar

Right. But just send to model a standard formated date. I suppose you use repositories.

afrayedknot's avatar

Actually - I've created a config file of 'default' locale settings.

Then I've created a middleware like this:

<?php

namespace App\Http\Middleware;

use Illuminate\Contracts\Auth\Guard;
use Closure;
use Config;

class SetLocaleConfig {

    protected $auth;


    public function __construct(Guard $auth)
    {
        $this->auth = $auth;
    }


    public function handle($request, Closure $next)
    {
        if ($this->auth->check()) {
            Config::set('locale.date_format', auth()->user()->date_format);
        }

        return $next($request);
    }
}

So I can safely call config('locale.date_format') throughout my application - and it will work

Please or to participate in this conversation.