Skip to content

Instantly share code, notes, and snippets.

@rakeshsoni18
Created June 10, 2020 13:15
Show Gist options
  • Save rakeshsoni18/3af6a1dd74e008f301b5d3f11e0b59ce to your computer and use it in GitHub Desktop.
Save rakeshsoni18/3af6a1dd74e008f301b5d3f11e0b59ce to your computer and use it in GitHub Desktop.
Assessor and Mutators
function getNameAttribute($value){
return strtoupper($value);
}
App\Dogs::find(2)->name; // result "JOCK"
That's a nice way to format database records before they hit the page, although it means that name will always be formatted that way (you can use ->getOriginal('name') if you need to see it without the formatting).
Here's a little secret, though. Add this to your Dogs model:
function getIdNameAttribute(){
return $this->attributes['id'] . ':' . $this->attributes['name'];
}
and access it with:
App\Dogs::find(2)->idName; // result "2:Jock"
Mutators:
Mutators are just the flip side of accessors. They let you capture the value before it goes into the database, so that you can do things like encrypt passwords or clean your data. So for example:
function setNameAttribute($value){
return $this->attributes['name'] = strtoupper($value);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment