create function as attribute in model laravel 8 and access in controller

Viewed 28

I have a dude with build a function in my model as attribute to do a avg calculate. I have a "posts" table that it´s filled by Curl with API. After y have a function that calculate rating with received params in this function. Next i need get data post with rating and insert in my db. In next step i need get all post order by ranting. To do this i build a function in my model.

/**
     * Calculate avg from column rating
     */
    public function getRatingCountAttribute() 
    {
        $rating = DB::table('posts')
                    ->select('posts.*')
                        ->addSelect(DB::raw('AVG(rating) as rating'))
                            ->groupBy('posts.id')
                            ->orderBy('rating');
    return $rating;
    }

i change my function rating in my model:

/**
     * Calculate avg from column rating
     */
    public function avg_rating() 
    {
        $rating = DB::table('posts')->groupBy('id')->avg('rating');
        
    return $rating;
    }

I have a function in my controller that sould return all my user with his post and i´m traying to access to my function with wrong result:

/**
     * Function to return users withs post
     * 
     * @return json with users and post
     */
    public function users()
    {
        $result = User::with('posts')->get();

        print_r($result[0]->rating_count);
        exit();

        print_r($result->rating_count);
        exit();

        return json_encode($result);
    }

protected $appends = ['rating_count']; // this is model

don´t return anythings. And i can show all my object without my attribute:

[0] => App\Models\Post Object ( [connection:protected] => sqlite [table:protected] => posts [primaryKey:protected] => id [keyType:protected] => int [incrementing] => 1 [with:protected] => Array ( ) [withCount:protected] => Array ( ) [preventsLazyLoading] => [perPage:protected] => 15 [exists] => 1 [wasRecentlyCreated] => [escapeWhenCastingToString:protected] => [attributes:protected] => Array ( [id] => 1 [user_id] => 1 [title] => sunt aut facere repellat provident occaecati excepturi optio reprehenderit [body] => quia et suscipit suscipit recusandae consequuntur expedita et cum reprehenderit molestiae ut ut quas totam nostrum rerum est autem sunt rem eveniet architecto [rating] => 32 [created_at] => 2022-09-15 07:57:26 [updated_at] => 2022-09-15 08:08:33

How i can to call this function or to do this?.

also i can say that if my function avg it´s wrong, what it´s the best way to do this?.

thanks and rewards

0 Answers
Related