Search code examples
laravellaravel-5.3

Laravel - Make global variable in Model to use only inside the Model


I have two variables in my Model that i use in a few functions

$firstDayThisYear = Carbon::create(date('Y'), 1, 1, 0);
$lastDayThisYear = Carbon::create(date('Y'), 12, 31, 0);

how can i extract them and make them global to use them only inside of my Model?

i know it must be protected...but I am not sure if i need to put it like this:

protected static $firstDayThisYear = Carbon::create(date('Y'), 1, 1, 0);
protected static $lastDayThisYear = Carbon::create(date('Y'), 12, 31, 0);

Solution

  • If you're going to use these variables in one model, just do this:

    protected $firstDayThisYear;
    
    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);
    
        $this->firstDayThisYear = Carbon::create(date('Y'), 1, 1, 0);
    }
    

    Then use it with $this->firstDayThisYear.

    Also, you could get start of the year and start of the last day of the year with:

    Carbon::now()->startOfYear();
    Carbon::now()->endOfYear()->startOfDay();
    

    I guess it's more readable.