1
I just faced a problem in Laravel 5.1.
Suppose I have the following:
Model
class User extends Model{
# Mutator
public function getNomeUpperAttribute(){
return strtoupper($this->attributes['nome']);
}
}
Controller
public function index(){
$user = User::find(1);
$user->nome_upper;
}
Return
UPPERCASE NAME
But let’s assume I did a JOIN for Eloquent and nay select the field name table Users.
public function index(){
$user = User::join('enderecos', 'enderecos.id_user', '=', 'users.id')
->select('rua', 'bairro', 'numero', 'cep')
->where('id_user', '=', 1)
->first();
}
When this happens the page gives an error:
Undefined index 'name';
This happens because it enters the function I defined in the Model Users.
To make no mistake, I have to make a check like this:
public function getNomeUpperAttribute(){
if(array_key_exists('nome', $this->attributes))
return strtoupper($this->attributes['nome']);
else
return null;
}
But imagine that I have several Accessors to customize various fields. I would have to do this check on all.
The question is:
in that case it is not
mutators
isserialization
if I’m not mistaken? I’m basing it on the spelling !!!– novic
In that case, it’s not Mutators, and yes Accessors.
– Wallace Maxters