skip to Main Content

When I retrieve some elements from the DB with Model::all() or any other such as Model::with(['otherModel')], I get an object with a different date from what the DB shows.

On my db:

Column 'created_at' on my DB

It shows the proper time. But when I query them:

A console log of one of those rows

The red arrow is the result of the created_at column, and the green arrow is a date I inserted on the controller when is created with Carbon, like this:

public function store(Request $request) {
    $request->validate([
        'monto' => 'required',
        'tasa' => 'required',
    ]);

    $request['fecha'] = Carbon::now();
    $request['total'] = 0;

    try {
        Cuenta::create($request->all())->save();

        return response()->json(['ok' => 'ok'], 200);
    } catch (QueryException $ex) {
        $res = $ex->getPrevious()->getMessage();

        return response()->json([
            'response' => $res,
        ]);
    }
}

As you can see, the Carbon date is working well. It saves it on my DB with the right timezone and retreives it with the same date. Instead, the timestamp that automatically sets the time is working well on the DB, but after querying it it changes

I have setted my laravel project timezone to match mine, and I also setted the timezone on SQL just in case, but still doesnt seems to work

I tried

To query a row from the DB with the laravel Model::with() (or ::find, any of them) function

I was excpecting

Same data as the DB

I received

A different date in all rows

2

Answers


  1. You should try this:
    change timezone in config/app.php

    'timezone' => 'UTC',
    

    to whatever timezone you want for example:

    'timezone' => 'Asia/Karachi',
    
    Login or Signup to reply.
  2. Try this way

    // App/Providers/AppServiceProvider.php
    
    public function boot()
    {
        date_default_timezone_set('Asia/Karachi'); // config('app.timezone')
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search