How to use Laravel's append Method: Enhancing Your Models with Custom Attributes

 How to use append method in Laravel

How to use Laravel's append Method: Enhancing Your Models with Custom Attributes


In this article we are going to demonstrate what's the use of append method and how can you use it efficiently in Laravel. append method is one of the powerful tool provided by Laravel which is very simple to use yet not many developers not aware of this.

What is the append Method ? :

Attribute methods used to add computed attributes / values to our model instance. These attributes are not a part of database or not a part of your eloquent query. It being computed over your query response. 

For Example: Let's say i have a query to fetch users and posts being posted by users and a user can have multiple posts and In the response i want total count of posts for each user. Here in this case we can make use of attributes and get our post count very easily. We will see the same in the below code as well.

Benefit of using append method are as follows :
  • Very easy to use
  • Make our code cleaner
  • Reusability
  • Better API response
Let's see how to use ' append ' method along with other methods with a proper example. Here we will take the example of user and posts. Let's create an api to fetch users and their posts and use attributes in it.

Route : 

Route::get('getusers',[HomeController::class,'getUsers'])->name('users.getusers');

User.php

<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use App\Models\Post;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $appends = ['count_posts'];


    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token'
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
    public function posts(){
        return $this->hasMany(Post::class,'user_id','id');
    }
    public function getCountPostsAttribute(){
        return $this->posts()->count();
    }
}


Here in the above code if you notice carefully, we have defined a variable named $appends and a method named getCountPostsAttribute().  The syntax of creating a attribute method is as follows.

get{Attribute_Name_With_Each_Words_First_Alphabet_Capital}Attribute

So here getCountPostsAttribute() method returns the post count.

With the above code whenever you fetch data from model a new key named count_posts automatically will be added to your response. let's say here is the following is our controller code.

HomeController.php :

<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Post;

class HomeController extends Controller
{
    public function getUsers(){
        try{
            $users = User::with('posts')
            ->limit(5)->get();
            return $users;
        }catch(\Exception $e){
            return false;
        }
    }
}

Response :

How to use Laravel's append Method: Enhancing Your Models with Custom Attributes


So here you can see a new key named count_posts automatically appended. Similarly here are some other methods provided by Laravel to make use of append method efficiently.

makeHidden() :

Let's say due to some requirements you do not to add this default key to your response in some queries. In such cases you can use makeHidden method which will hide your attribute from being exposed in response.

<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Post;

class HomeController extends Controller
{
    public function getUsers(){
        try{
            $users = User::with('posts')->limit(5)->get();
            return $users->makeHidden('count_posts');
        }catch(\Exception $e){
            return false;
        }
    }
}

MakeVisible() : 

Let's say you have created some attributes in your model but made them hidden by putting them inside the $hidden variable like the following.

protected $hidden = [
        'password',
        'remember_token',
        'count_posts'
    ];

Now you want to access those attributes on some of your selected queries only. In that case you can make use makeVisible() method as follows.

<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Post;

class HomeController extends Controller
{
    public function getUsers(){
        try{
            $users = User::with('posts')->limit(5)->get();
            return $users->makeVisible('count_posts');
        }catch(\Exception $e){
            return false;
        }
    }
}

Apart from this, there other methods as well provided by Laravel to make efficient use of append attributes.


Previous Post Next Post

Contact Form