0

The laravel 6.x returns the output as an array instead of an object when accessing the relationship in one pc it supports the array and on the other pc, it only supports the object.

class Category extends Model
{

    public function parent() {
        return $this->belongsTo(Category::class,'parent_id');
    }

    public function children() {
        return $this->hasMany(Category::class,'parent_id');
    }

}

on the blade page this can be accessed like below

 @foreach ($categories as $category)
   <tr>

     <td >{{$category->parent['name']}}</td>
   </tr>
 @endforeach
4
  • In my laravel (6 too) it's not happen, try to use "get()" method from any of the methods above and see what's happen, if is an array will return an error, if not return an error so it's means that the new version of laravel don't depend of the "get()" method anymore. Commented Jan 23, 2020 at 14:44
  • $category->parent->name and $category->parent['name'] are both valid in Laravel; Models are accessible via either syntax, but the preferred method is object access (->). Commented Jan 23, 2020 at 14:44
  • @TimLewis, Do you know the reason for these two type of different issues. How to change the array to object? Commented Jan 23, 2020 at 14:52
  • Like the answer says below, it's not an array, unless you call ->toArray(). I've never seen the issue with one method of access ->name not working vs the other ['name']. Commented Jan 23, 2020 at 15:09

1 Answer 1

1

Eloquent models implement ArrayAccess.

So $category->parent->name should work the same as $category->parent['name'].

It's not actually an array it just is accessible like one.

Sign up to request clarification or add additional context in comments.

Comments

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.