Rodney Wormsbecher Rodney Wormsbecher - 4 months ago 46
PHP Question

Include/call external class in laravel

Even though I have seen multiple questions like this in stackoverflow, I still wasn't able to get my custom php class working in laravel. I have done the following:

laravel -> app -> Libraries -> DateFunction.php as my filepath

The actual DateFunction.php contains the following code

<?php

namespace App\Libraries;

class DateFunction
{
public $timeWorked;

public function getRealHours($time) {
if ($time / 60 < 1) {
$this->timeWorked = $time . "m";
} else {
$hours = $time / 60;
$minutes = $time % 60;

$this->timeWorked = $hours . "h" . $minutes . "m";
}

return $this->timeWorked;
}

}


In my controller I have used
use App\Libraries\DateFunction;


But in my View when I use

@foreach ($labourentries as $labour)
<tr>
<td>{{ $labour->labourtype_id }}</td>
<td>{{ getRealHours($labour->minutes_worked) }}</td>
</tr>
@endforeach


it still give me the error: Call to undefined function getRealHours()

Any help would be much appreciated. Cheers

Answer

When you write use App\Libraries\DateFunction only have available the DateFunction class in this controller, and you should use it as follows:

Class AlohaController 
{

    public function something()
    {
        $InstanceClass = new DateFunction;
        $realHour = $InstanceClass->getRealHours(48);
    }
}

If you want to use globally getRealHours() You do not need to have a class.

If you want to create a function helper you have to do the following:

  1. edit the file composer.jsonputting the path of your helper file

    enter image description here

  2. run composer dumpautoload to generate the bootstrap file

  3. Helpers file should look like this:

    function getRealHours($time) {
    
        $timeWorked = 0;
    
        if ($time / 60 < 1) {
            $timeWorked = $time . "m";
        } else {
            $hours = $time / 60;
            $minutes = $time % 60;
    
            $timeWorked  = $hours . "h" . $minutes . "m";
        }
    
        return $timeWorked;
    
    }
    

Another possible solution

In your controller creates an instance of the DateFunction class and send it to your view.

Your controller should look like this:

$helpers = new DateFunction;
return view('path.to.view', ['helpers' => $helpers]);

And in your view you could use it in this way:

<td>{{ $helpers->getRealHours($labour->minutes_worked)  }}</td>