Alex Alex - 16 days ago 4
PHP Question

Laravel 5.2 - edit the data from DB in the Model

Can I check and edit data in Model, not in Controller?
For example, now I get data from Model and work with it in Controller.

$user = User::select('name','privateflag','lastname')->get();
//name = John, privateflag = 1, lastname = Smith
if ($user->privateflag == 1) {$user->lastname = 'Private';}
//Pass to View: name = John, lastname = Private


Can I check and edit data in Model and receive in Controller already updated data? Like this:

class User extends ... {
...
//Get from DB: name = John, privateflag = 1, lastname = Smith
if ($user->privateflag == 1) {$user->lastname = 'Private';}
//Pass to Controller: name = John, lastname = Private
}

Answer

The recommended way is to use accessors in model like this:

class User extends Model {
...
public function getLastNameAttribute()
{
    if ($this->privateflag) {
        return 'Private';
    }
    return $this->attributes['lastname'];
}