change the date format in laravel view page

前端 未结 11 2168
-上瘾入骨i
-上瘾入骨i 2020-12-02 06:23

I want to change the date format which is fetched from database. now I got 2016-10-01{{$user->from_date}} .I want to change the format \'d-m-y\' in laravel

11条回答
  •  半阙折子戏
    2020-12-02 06:48

    I had a similar problem, I wanted to change the format, but I also wanted the flexibility of being able to change the format in the blade template engine too.

    I, therefore, set my model up as the following:

    The setToStringFormat will set all the dates to use this format for this model.
    The advantage of this for me is that I could have the format that I wanted without the mutator, because with the mutator, the attribute is returned as a string meaning that in the blade template I would have to write something like this if I wanted to change the format in the template:

    {{ date('Y', strtotime($user->from_date)) }}
    

    Which isn't very clean.

    Instead, the attribute is still returned as a Carbon instance, however it is first returned in the desired format.
    That means that in the template I could write the following, cleaner, code:

    {{ $user->from_date->format('Y') }}
    

    In addition to being able to reformat the Carbon instance, I can also call various Carbon methods on the attribute in the template.

    There is probably an oversight to this approach; I'm going to wager it is not a good idea to specify the string format at the top of the model in case it affects other scripts. From what I have seen so far, that has not happened. It has only changed the default Carbon for that model only.

    In this instance, it might be a good set the Carbon format back to what it was originally at the bottom of the model script. This is a bodged idea, but it would work for each model to have its own format.
    Contrary, if you are having the same format for each model then in your AppServiceProvider instead. That would just keep the code neater and easier to maintain.

提交回复
热议问题