How to get an attribute throw a table in Eloquent?



I have requests table that belongs to subcategories table which belongs to categories table, so from Request model how can I get an attribute from categories?

tables

->requests
id
name
subcategory_id


->subcategories
id
name
category_id


->categories
id
name
color

So I need to get color from Request model, I already have the tree models created

class Request extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class)->get();
    }

    public function color()
    {
        $somemagicstuff;
        
        return $color;
    }
}

Answer

You need to define your relationships:

# Request.php

class Request extends Model
{  
    public function subcategory()
    {    
        return $this->belongsTo(Subcategory::class);
    }
}

# Subcategory.php

class Subcategory extends Model
{  
    public function category()
    {    
        return $this->belongsTo(Category::class);
    }
}

Then you could just do:

$color = Request::first()->subcategory->category->color;

Of course, you can add a computed attribute to your Request class to easy access (keep in mind that this could increase the number of queries):

# Request.php

class Request extends Model
{  
    public function subcategory()
    {    
        return $this->belongsTo(Subcategory::class);
    }

    public function getColorAttribute()
    {    
        return $this->subcategory->category->color;
    }
}

Then:

$color = Request::first()->color;


Source: stackoverflow