I am trying to call App\Http\Timeslot::isOpen()
from my blade view but I don't understand how to call this without declaring the isOpen() as static. I can't declare it as static as I need to use $this->hours from the construct. If I don't declare it static laravel returns Cannot redclare Class error
Could someone suggest how I should write this so that I can still access the $this->hours variable?
Blade Template:
@if(App\Http\Timeslot::isOpen())
We're open
@else
We're closed
@endif
Timeslot Class
<?php namespace App\Http;
use App\OpeningHour;
use Carbon\Carbon;
class Timeslot
{
protected $hours;
public function __construct()
{
$this->hours = OpeningHour::all();
}
public static function isOpen()
{
// get current date
Carbon::now()->format('w');
$open_window = $this->hours->get(Carbon::now()->format('w'));
// is it over current days' opening hours?
if(Carbon::now()->toTimeString() > $open_window->opening_time)
return true;
else
return false;
}
}
You could declare $hours as static too, and call a method inside isOpen() to retrieve/cache them.
Something like :
Like this, you don't have to use a constructor.
Another way to go (maybe a more 'Laravelish' way) would be to migrate your class into a Service provider : https://laravel.com/docs/5.3/providers
Look for "View composers", they are ways to inject data into your views.