Friday, July 13, 2018

Note : Using hidden for Laravel's model $append

Eloquent's mutator has been very helpful for making an additional attribute to a model. What is Eloquent mutator? According to Laravel's documentation, it says 

Accessors and mutators allow you to format Eloquent attribute values when you retrieve or set them on model instances.

Mutator is use along with an accessor, before accessor I usually use a method to return a custom field. For instance, I wanted my user model to return full name or lastname, firstname field. I would do the following


class User extends Model {
          public function fullname(){
                   return $this->firstname . " " . $this->lastname;
         }
}

My issue from above code is that I have to execute it each time I wanted to use it. Wouldn't it be nice if it's already attached along with your other attributes? How to do it?

Based on Laravel's documentation, accessor must be defined like a getter.

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{

    public function getFullNameAttribute()
    {
        return ucfirst($this->firstname) . " " . ucfirst($this->lastname);
    }

}
To attach it to the request just like the other attributes $appends property shall be added to the model.

The model will look something like this.
<?php 
namespace App; 
use Illuminate\Database\Eloquent\Model;
class User extends Model {
    protected $appends = array('fullname');
 
Since I'm using the append, mutators and accessors to a related table I noticed that related table will also be attached. Like in my post table, my post will have a user object attached into it. Check out the screenshot below. You will notice that user is attached to the post model. But I only wanted to append my custom field author.



Solutions:


  1. Add 'user' to the hidden property of the model and it will automatically hide the user object like this.
  2. Loop to the post collection and use the model method "makeHidden()". like this
           foreach($posts as $post){
                $post->makeHidden('user');
           }


And now the result will be something like this.

By using makeHidden, you can dynamically hide the mutator related table like user in my case. If it's in the hidden property of the model then it will not be in the attributes anymore. Unless the opposite  of makeHidden makeVisible method is use on the model.


No comments:

Post a Comment