简体   繁体   中英

accessor not working in laravel 5.5

I have a model that have one accessor inside it

class Test extends Model
{
    protected $fillable = [
        'subject','date',
   ];


    public function getSubjectAttribute($value)
    {
        return ucfirst($value);
    }
}

When I call model, accessor does not work I read all documents and Q&A , but ... My Laravel version in 5.5

In the model I have a method for fetch data

public function get_specific_subject($id){
    $subject = DB::table("subjects")
        ->where("id", "=", $id)
        ->first();

    return $subject;
}

And I am calling this method in my controller by bellow code

    $subject = new Test();
    $subject = $subject->get_specific_subject($subject_id);
    dd($subject);

The dd result is :

    +"id": 5
    +"subject": "testing subject"
    +"date": "2018-01-17"
    +"created_at": "2018-01-13 15:08:41"
    +"updated_at": "2018-01-13 15:08:41"

You are using DB to fetch your record , instead do this in your controller :

  $subject= Test::find($subjectId);
  dd($subject);

and in your model , add this line :

  protected $table = 'subjects';
  public $primaryKey='id';
class Test extends Model
{
   protected $table = 'subjects';
   protected $fillable = [
       'subject','date',
   ];

   public function getSubjectAttribute($value)
   {
       return ucfirst($value);
   }
}

And in controller

public function view($subjectId){
    $subject = Test::find($subjectId);
    dd($subject->toArray());
}

使用$subject->subject代替。

Change your code like this (use your model):

public function get_specific_subject($id){
    $subject = Subject::where("id", "=", $id)
        ->first();
    return $subject;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM