vendredi 26 août 2016

Laravel 5 returns JSON instead of object on belongsTo() relationship

I have installed Laravel framework v5.3.2 and dimsav/aravel-translatable package v6.0.1. I'm having problem with getting data from belongsTo() relationship (parent) on same model.

Category.php model

class Category extends Eloquent
{
    public $translatedAttributes = [
        'name', 'slug', 'description'
    ];

    public function category()
    {
        return $this->belongsTo('App\Model\Category', 'category_id', 'id');
    }

    public function categories()
    {
        return $this->hasMany('App\Model\Category', 'category_id', 'id');
    }
}

When I print name attribute in view, Laravel throws exception: "Trying to get property of non-object".

<?php echo $category->category->name; ?>

But when I try to get value as array it works:

<?php echo $category->category['name']; ?>

Method for getting list of all categories:

$categoryModel = new Category;
$categories = $categoryModel->with('category')->get();

One more thing, when i try to var_dump($category->category) i get this:

object(App\Model\Category)[221]...

So the object exists but Laravel does not show it properly when i try accessing the attribute directly. Anyone knows where the problem is? Is it in Laravel or maybe in laravel-translatable package?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2blcT4K
via IFTTT

Aucun commentaire:

Enregistrer un commentaire