binggle
binggle

Reputation: 25

How to get property or method in relationship ( laravel - eloquent )

in Post Model

function user()
{
    return $this->belongsTo( \App\User::class);
}

in User Model

function posts()
{
    return $this->hasMany( \App\Post::class);
}


function somedata() 
{
    return  date('i') * 1000  + date('s'); 
}

in Controller

$posts = Post::query()
        ->where('id', 10)
        ->with('user')
        ->get();

but it does not get 'somedata' in user model .

How can I drag this data with posts ?

Upvotes: 0

Views: 701

Answers (2)

You need to set an Accessor:

    <?php

    namespace App;

    use Illuminate\Database\Eloquent\Model;

    class User extends Model
    {
        /**
         * Get the user's somedata.
         *
         * @return string
         */
        public function getSomedataAttribute()
        {
            return 'somedata';
        }
    }

Also see: https://laravel.com/docs/5.8/eloquent-mutators

Upvotes: 0

Salim Djerbouh
Salim Djerbouh

Reputation: 11034

Try making it an attribute and append it in the model
Post.php

/**
 * The accessors to append to the model's array form.
 *
 * @var array
 */
protected $appends = ['someData'];

/**
 * Get the some data for the post.
 *
 * @return int
 */
public function getSomeDataAttribute()
{
    return  date('i') * 1000  + date('s');
}

Upvotes: 2

Related Questions