Skip to content

Add casting closures in eloquent models #52494

Answered by shaedrich
shivam-bmn asked this question in Ideas
Discussion options

You must be logged in to vote
class Settings extends Model
{
    protected $casts = [
        'setting' => 'column:setting_type',
    ];
}

When the database looks like this:

id setting setting_type
1 1 int
2 2024-09-28 22:54:00 date
3 lorem ipsum ahmet sun string

Then, the model will look like this:

dump(Settings::find(1)->setting); // prints 1
dump(Settings::find(2)->setting); /* prints Carbon\Carbon @1727556978 {#1881 ▼
  #constructedObjectId: "0000000031bf18760000000007f7b216"
  #localMonthsOverflow: null
  #localYearsOverflow: null
  #localStrictModeEnabled: null
  #localHumanDiffOptions: null
  #localToStringFormat: null
  #localSerializer: null
  #localMacros: null
  #localGenericMacros: null
  #lo…

Replies: 2 comments 3 replies

Comment options

You must be logged in to vote
1 reply
@shivam-bmn
Comment options

Comment options

You must be logged in to vote
2 replies
@henzeb
Comment options

@shaedrich
Comment options

Answer selected by shivam-bmn
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Ideas
Labels
None yet
3 participants