skip to Main Content

i am casting an array

[1,2]

and in my model I have this setup

    protected $casts = [
      'skills' => 'array'
    ];

and I have my relationship setup like this

    public function skills(){
      return $this->hasMany(Skill::class,'id');
    }

now my problem is my skills relationship only returns the first value here is the return data

            "skills": [
             {
                "id": 1,
                "name": "Angularjs",
                "created_at": "2024-10-08T05:03:38.000000Z",
                "updated_at": "2024-10-08T05:03:38.000000Z"
             }
           ]

2

Answers


  1. it is possible you are forgeting something.for example check the deleted at column of your database table,maybe you have used soft delete,and table still is showing the data,If not,please send me more info to help you

    Login or Signup to reply.
  2. To quote the Laravel docs:

    Attributes that are null will not be cast. In addition, you should never define a cast (or an attribute) that has the same name as a relationship or assign a cast to the model's primary key.

    https://laravel.com/docs/11.x/eloquent-mutators#attribute-casting

    That said, the cast as defined above would cast a JSON database column called "skills" to an array. This will not work for a relationship.

    To access the relationship data as an array, either do

      $yourModelInstance->skills()->all();
    

    to get an array of Skill instances (objects), or

      $yourModelInstance->skills->toArray()
    

    to get an array of Skills that are cast into an associative array.

    It also looks like the variable dump is JSON, probably from Javascript. If you are passing data to a frontend, it might be a good idea to look into Eloquent Resources: https://laravel.com/docs/11.x/eloquent-resources

    It is a good practice to define how to deliver data to the frontend that doesn’t accidentally contain data you don’t need or don’t want to be posted to the frontend. You can also use the $hidden or $visible properties on any Model.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search