Mohamed Benhida

admin@devma.net

January 9, 2018

Tip - Best Way For Passing Model Attributes For an API

Today, We will talk about the best way to pass the attributes to a Model Array 

We often, override the toArray() function so we can see the new Attributes on Model Array

App\Post.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model {

    public function owner()
    {
        return $this->belongsTo('App\User', 'user_id');
    }

    public function isAdmin()
    {
        return $this->owner->admin == 1;
    }

    public function toArray()
    {
        return array_merge(parent::toArray(),[
            'is_admin' => $this->isAdmin()
        ]);
    }

}

But if i told there is a better method using $appends something that no much people know about it.

We just have to add a new Attribute to our class Model using this function getNameAttribute()

App\Post.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model {
    protected $appends = ['is_admin'];

    public function owner()
    {
        return $this->belongsTo('App\User', 'user_id');
    }

    public function getIsAdminAttribute()
    {
        return $this->owner->admin == 1;
    }

}

If you pass a relation to this attribute it will also append on the Array like this without using $with

post

If you have a question email me with it im glad to help.

© Mohamed Benhida.

Blog | Packages | About