phplaravelvirtual

Laravel virtual column in model


I have one question, how can I create a virtual column ( computed ) in the model?

I searched and just found how to set Attributes, but I need a virtual column, for example, if I will call Post::all() there must be that virtual column called title_body for example:

$post->title . ' ' . $post->body

and in Post:all(); i must get that column. How can I do this? is it possible?


Solution

  • Use $appends like in your Post model:

    /**
     * Appends
     * @var array
     */
    protected $appends = [
        'title_body',
    ];
    
    public function getTitleBodyAttribute()
    {
        return $this->title . ' ' . $this->body;
    }