Posted: 07-11-2020

How to get a model original attribute value with getRawOriginal in Laravel

How to get a model original attribute value with getRawOriginal in Laravel

From Laravel 7.x is. available the getRawOriginal to get the model's raw original attribute values.

I think everyone uses Laravel accessors to format Eloquent attribute values when you retrieve them from model instances.

For example if you need to format a date attribute you can define an accessor like this:

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

The result is:

//retrive the date attribute
$model->date => "09-10-1964

Bu in some case you need to retrieve the original value stored in the DB, for example:

function getNextNews($current_news){
 
\App\News::where('date', '>', $current_news->date)->first(); }

This code produces the following query

select * from `news` where `date` > '11-07-2017' limit 1

as you can notice the date format is wrong d-m-Y instead of Y-m-d as stored in DB.

In this situation you can use the getRawOriginal methods available in Laravel from version 7.x

function getNextNews($current_news){
 
\App\News::where('date', '>', $current_news->getRawOriginal('date') )->first(); }

that return the date value in the correct format
select * from `news` where `date` > '2017-07-11' limit 1