0

I have a problem here, I want to add one column from the result of the relation, namely the percentage column, this column is the result of pagebook / pageread * 100 this is my result db what I want

"id": 2,
    "id_book": 2,
    "id_user": 2,
    "pageread": 120,
    "books": {
                "id": 2,
                "pagebook":125
             }
    "percentage":96

this is my code in controller

$book= Read::with('books.authors')->where('id_user',$user->id)->get();

and this my code in model

public function books()
    {
        return $this->belongsTo(Book::class,'id_book','id');
    }
1

2 Answers 2

1

you can do it in the model:

class YourModel ...{
    protected $appends = ['percentage'];
    public function getPercentageAttribute()
    {
        return /* the calculation that you need */
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

how can i send parameter book->pagebook and pageread to getPercentageAttribute for calculate?
@Newbie123 same way you would have done in a controller or anywhere else
0
 protected $appends = ['percentage'];
    public function getPercentageAttribute()
    {
        $read= $this->pageread;
        $book= $this->books->pagebook
        return $read/$book*100


    }

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.