lewis4u lewis4u - 23 days ago 5
PHP Question

Laravel Model function using relationship

I made this function in my view for summing total hours

<?php

$sum = [];
foreach($user->workedTimes as $item){
array_push($sum, ($item->end_time->diffInHours($item->start_time)));
}
echo array_sum($sum);

?>


And in blade view all is fine, but i want that same code in my Model so i can call user->totalHours in blade

and i made this function in my Model:

enter image description here

and when i call {{ $user->totalHours }}

i get this error:

enter image description here

How to make this work from Model??

Answer

You should use the method with brackets like this:

{{ $user->totalHours() }}

But it would be good if you use Laravel Accessor like this:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    public function getTotalTimeAttribute()
    {
       // Your logic here ...
       $sum = [];
       foreach($this->workedTimes as $item) {
         array_push($sum, $item->end_time->diffInHours($item->start_time));
       }
       return array_sum($sum);
    }
}

and access it in blade like this:

{{ $user->total_time }}

Hope this helps!