'Adding a variable into a custom table in Laravel

I have a table which is a combination of 3 tables being passed to my blade file.

 $late_books = Borrow::join('books', 'borrows.book_id', '=', 'books.id')
                                        ->join('borrowers', 'borrows.borrower_id', '=', 'borrowers.id')
                                        ->where('borrows.late_return_status', '=', 1)
                                        ->where('borrows.return_date', '=', null)
                                        ->get(['borrowers.borrower_name', 'borrowers.IC', 'borrowers.phone_no' ,'books.ISBN', 'books.book_title', 'books.year','books.author', 'books.publisher_name',
                                            'borrows.issue_date', 'borrows.due_date']);

Within the blade file, i need to add a button which has the fines.

$due_date = \Carbon\Carbon::parse($late_books->first()->due_date);
$today = \Carbon\Carbon::now();
$result = $due_date->diffInDays($today);
$fine = $result * 5;

The fine should be specific to each book borrowed, the current way ive done it shows same fine for all books.

return view('admin.latereturn', compact('late_books', 'search', 'fine'));

Im sure this question has been asked in some form before but im not exactly sure what to search. Sorry if it's a duplicate.



Solution 1:[1]

If i get you

you can Defining An Accessor for appending attribute inside your model as the following:

class Borrow extends Model
{
 protected $appends = ['fine'];

 public function getFineAttribute()
  {
   $due_date = \Carbon\Carbon::parse($this->due_date);
   $today = \Carbon\Carbon::now();
   $result = $due_date->diffInDays($today);
   $fine = $result * 5;
   return $fine;
  }
}

and you can access fine attribute inside your blade as $model_instance->fine

       @foreach($late_books as $lb)
        <span> {{$lb->fine}} </span> 
       @endforeach 

I hope this helpful for you

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1