2

I am trying to override the laravel eloquent model constants for created_at and updated_at:

namespace App;

use Illuminate\Database\Eloquent\Model;

 class Visit extends Model
 {
    const CREATED_AT = 'creation_date';
    const UPDATED_AT = 'last_update';
 }

and then get the latest entry:

dd(Visit::latest()->get());

but am getting an unknown column error:

"SQLSTATE[42S22]: Column not found: 1054 Unknown column 'created_at' in 
'order clause' (SQL: select * from `visits` order by `created_at` desc)"

Is there anything else that needs to be done to get this working?

Zach Abrams
  • 93
  • 1
  • 7

2 Answers2

7

latest() always uses created_at by default. You have to specify the column name yourself:

Visit::latest(Visit::CREATED_AT)->get();

You can override the default behavior by adding a local scope to your Visit model:

public function scopeLatest($query)
{
    return $query->orderByDesc(static::CREATED_AT);
}

UPDATE: This will be fixed in Laravel 5.7: https://github.com/laravel/framework/pull/24004

Jonas Staudenmeir
  • 24,815
  • 6
  • 63
  • 109
  • That's it, [here's the source](https://github.com/laravel/framework/blob/5.6/src/Illuminate/Database/Query/Builder.php#L1579), column `created_at` is hardcoded. – DevK Apr 06 '18 at 22:03
  • Or you can do Visit::latest('any_col_you_want')->get() , but I like the way Jonas' answer ties it all together nicely. – Tarek Adam Apr 06 '18 at 22:07
  • Is there any way to override the default other that specifying the column name on latest()? In the source those the default values. In the documentation it says you can override the defaults on a model by model basis. Doesn't seem to be working. – Zach Abrams Apr 06 '18 at 22:09
  • I extended my answer. – Jonas Staudenmeir Apr 06 '18 at 22:19
  • Thank you! Do you have any clue as to what the documentation is referring to here: https://laravel.com/docs/5.6/eloquent where it says: If you need to customize the names of the columns used to store the timestamps, you may set the CREATED_AT and UPDATED_AT constants in your model: – Zach Abrams Apr 06 '18 at 22:24
  • When creating and updating models Laravel uses custom `CREATED_AT`/`UPDATED_AT` columns as expected. The `latest()` method is an exception. – Jonas Staudenmeir Apr 06 '18 at 22:31
  • This will be fixed in Laravel 5.7: https://github.com/laravel/framework/pull/24004 – Jonas Staudenmeir Apr 25 '18 at 18:31
0

Cause the latest get the created_at by default check here maybe for here Same problem as you and same code

nicolassiuol
  • 83
  • 2
  • 12