0

I have a model called template and field template - when being called it doesn't exist, so how do I create a property or attribute called template when calling it this is being called through ajax. I tried making an accessor but it's not creating the attribute 'template' getTemplateAttribute($value) so I made a with('template') and I can't seem to create the attribute template in my model when being called.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Template extends Model
{
    protected $table = 'templates';

    protected $fillable = ['title', 'directory', 'filename', 'created_at', 'updated_at'];

    public function template() {
        $this->attributes['template'] = 'test';
    }
}

// and when calling it

public function show(Template $template)
{
    $template = Template::findOrFail($template->id)->with('template');
    return $template;
}
2
  • Do you get any error? Commented Oct 3, 2017 at 2:45
  • You need declare your custom attribute in your model. protected $appends = ['template'] and then you need to set your custom attribute Commented Oct 3, 2017 at 2:49

1 Answer 1

1

Use appends in model.. then use getAppendTypeAttribute(); the AppendType must be exact name as appends value..

class Template extends Model
{
    protected $table = 'templates';

    protected $fillable = ['title', 'directory', 'filename', 'created_at', 'updated_at'];

    protected appends = ['template'];


    public function getTemplateAttribute() {
        return "test";
    }
}

then

 $template = Template::findOrFail($template->id);
 return $template->template;
Sign up to request clarification or add additional context in comments.

1 Comment

im glad it helps.. you can mark this answer if it helps you. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.